时间:2018-12-19
概述:判断IP getAddress()
现在的 IP 地址是采用4 个字节32 位长度的标准,在下一代互联网中将采用16 个字节128 位的标准。在IP 地址分配中有A、B、C、D、E 这五种地址类型。本例通过编程实现了获得指定主机的IP 地
址长度和地址类型。运行程序后,程序输出为:地址长度为4;地址类型为C。
实现方法和思路:
通过 InetAddress 对象的getAddress()方法返回主机的IP 地址,将此IP 地址存入一个Byte 类型的数组里面,通过该数组的长度来判断该IP 地址的长度,根据其第一个元素来判断其为哪一类地址类型。编写代码:
1.编写useAddressKind 类的基本框架,在该类中包括返回值为整型的getVersion ()方法、返回值为字符类型的getClass ()方法和无返回值的main()方法:
public class useAddressKind
{
public static int getVersion(InetAddress ia);
public static char getClass(InetAddress ia);
public static void main (String[] args);
}
2.GetVersion()方法获得地址长度,代码如下:
//获得地址的长度
public static int getVersion(InetAddress ia)
{
byte[] address = ia.getAddress( );
if (address.length == 4) return 4;
else
if (address.length == 16) return 6;
else return -1;
}
3.GetClass()方法获得地址类型:
//获得地址类型
public static char getClass(InetAddress ia)
{
byte[] address = ia.getAddress( );
if (address.length != 4)
{
throw new IllegalArgumentException("No IPv6 addresses!");
}
int firstByte = address[0];
if ((firstByte & 0x80) == 0) return 'A';
else if ((firstByte & 0xC0) == 0x80) return 'B';
else if ((firstByte & 0xE0) == 0xC0) return 'C';
else if ((firstByte & 0xF0) == 0xE0) return 'D';
else if ((firstByte & 0xF8) == 0xF0) return 'E';
else return 'F';
}
4.Main()方法调用getVersion()方法获得地址长度,调用getClass()方法获得地址类型,代码如下:
public static void main (String[] args)
{
try
{
InetAddress ia=InetAddress.getByName("www.microsoft.com");
int len;
char kind;
len=getVersion(ia);
System.out.println("地址长度为"+len);
kind=getClass(ia);
System.out.println("地址类型为"+kind);
}
catch(UnknownHostException e)
{
System.err.println(e);
}
}
程序中使用了net 类,所以要在代码开头引入java.net.*包。