最近在作TCP,UDP协议的程序,都做完好几天了,最后测试完了,惊讶的发现我没指定IP居然程序一直运行正常,DEBUG后发现问题出现在InetAddress.getByName()方法上,这个方法即使主机名没指定,也可以确定主机的 IP 地址,即返回本机的IP地址127.0.0.1,很是意外!
import java.io.IOException;
import java.net.InetAddress;
public class TestInetAddressGetAddress {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String ip = "";
InetAddress ia = InetAddress.getByName(ip);
System.out.println(ia);
System.out.println("是否可以达到该地址:"+ia.isReachable(5000));
}
}运行结果:
localhost/127.0.0.1
是否可以达到该地址:true
本文探讨了在未明确指定IP地址的情况下,Java中InetAddress.getByName()方法的行为。通过示例程序验证了该方法会默认返回本地回环地址127.0.0.1,并且能够成功进行可达性测试。
1461

被折叠的 条评论
为什么被折叠?



