我想知道InetAddress对象在构造时是否使用主机名或IP地址进行初始化。有没有办法在java中检查这一点?
发布于 2013-06-11 01:23:07
可以,停那儿吧。
InetAddress.toString()返回以下格式的字符串表示:host-name/IP address。如果主机名未知(使用IP地址创建实例时会发生这种情况),则第一部分为空。
以下代码片段如下:
System.out.println(InetAddress.getByName("localhost").toString());
System.out.println(InetAddress.getByName("127.0.0.1").toString());
System.out.println(InetAddress.getByName("www.google.com").toString());
System.out.println(InetAddress.getByName("173.194.113.145").toString());打印以下输出:
localhost/127.0.0.1
/127.0.0.1
www.google.com/173.194.113.144
/173.194.113.145因此,您可以这样说:
public static boolean isCreatedFromIp(InetAddress addr) {
return addr.toString().startsWith("/");
}编辑:我没有和IPv6确认这一点,但我相信有类似的解决方案,因为toString()的实现不依赖于IP版本。
https://stackoverflow.com/questions/17029267
复制相似问题