为了区分IPv4和IPv6地址,Java提供了两个类:Inet4Address和Inet6Address,它们都是InetAddress类的子类,这两个类的定义如下:
Normal
0
7.8 磅
0
2
false
false
false
MicrosoftInternetExplorer4
这两个类分别按着IPv4和IPv6的规则实现了InetAddress类中的public方法。它们所不同的是Inet6Address类比Inet4Address类多了一个方法:isIPv4CompatibleAddress,这个方法用来判断一个IPv6地址是否和IPv4地址兼容。和IPv4兼容的IPv6地址除了最后四个字节有值名,其他的字节都是0,如0:0:0:0:0:0.192.168.18.10、::ABCD:FAFA都是和IPv4兼容的IPv6地址。 当使用InetAddress类的四个静态方法创建InetAddress对象后,可以通过getAddress返回的byte数组来判断这个IP地址是IPv4还是IPv6地址(byte数组长度为4就是IPv4地址,byte数组长度为16就是IPv6地址),也可以将instanceof来确定InetAddress对象是它的哪个子类的实例。下面的代码演示了如何判断一个IP地址是IPv4还是IPv6地址:
Normal
0
7.8 磅
0
2
false
false
false
MicrosoftInternetExplorer4
执行如下命令:
运行结果: 测试2 执行如下命令: 运行结果:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->package mynet;
import java.net.*;
public class MyIP
{
public static void main(String[] args) throws Exception
{
if (args.length == 0)
return;
InetAddress address = InetAddress.getByName(args[0]);
System.out.println("IP: " + address.getHostAddress());
switch (address.getAddress().length)
{
case 4:
System.out.println("根据byte数组长度判断这个IP地址是IPv4地址!");
break;
case 16:
System.out.println("根据byte数组长度判断这个IP地址是IPv6地址!");
break;
}
if (address instanceof Inet4Address)
System.out.println("使用instanceof判断这个IP地址是IPv4地址!");
else if (address instanceof Inet6Address)
System.out.println("使用instanceof判断这个IP地址是IPv6地址!");
}
}
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->java mynet.MyIP www.csdn.net
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->IP: 211.100.26.122
根据byte数组长度判断这个IP地址是IPv4地址!
使用instanceof判断这个IP地址是IPv4地址!
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->java mynet.MyIP
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->IP: 2001:da8:9000:b255:200:e8ff:feb0:5c5e
根据byte数组长度判断这个IP地址是IPv6地址!
使用instanceof判断这个IP地址是IPv6地址!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12921506/viewspace-592584/ ,如需转载,请注明出处,否则将追究法律责任。