最近在作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