直接上测试代码:
//解析域名返回多个IP地址
String domain = "www.google.com";
try {
InetAddress[] inetAddresses = InetAddress.getAllByName(domain);
// 输出所有的IP地址
System.out.println(Arrays.toString(inetAddresses));
for (InetAddress address : inetAddresses) {
if(address instanceof Inet4Address){
System.out.println("IPv4:"+address.getHostAddress());
}else if(address instanceof Inet6Address){
System.out.println("IPv6:"+address.getHostAddress());
}else{
System.out.println("IP is unknown"+address.getHostAddress());
}
}
//针对具体的IP判断
ip = "2001:0:0:0:0:0:0:1";
InetAddress address = InetAddress.getByName(ip);
if(address instanceof Inet4Address){
System.out.println(ip + " is an IPv4 address.");
}else if(address instanceof Inet6Address){
System.out.println(ip + " is an IPv6 address.");
}else{
System.out.println(ip + " is of unknown type.");
}
} catch (UnknownHostException e) {
System.err.println("Cannot resolve hostname: " + domain);
}