getAddress
方法和getHostAddress
类似,它们的唯一区别是getHostAddress
方法返回的是字符串形式的IP
地址,而getAddress
方法返回的是byte
数组形式的IP
地址。getAddress
方法的定义如下:
public
byte
[] getAddress()
这个方法返回的byte
数组是有符号的。在Java
中byte
类型的取值范围是-128
〜127
。如果返回的IP
地址的某个字节是大于127
的整数,在byte
数组中就是负数。由于Java
中没有无符号byte
类型,因此,要想显示正常的IP
地址,必须使用int
或long
类型。下面代码
演示了如何利用getAddress
返回IP
地址,以及如何将IP
地址转换成正整数形式。
package
mynet;
import java.net. * ;
public class MyIP
{
public static void main(String[] args) throws Exception
{
InetAddress address = InetAddress.getByName( " www.csdn.net " );
byte ip[] = address.getAddress();
for ( byte ipSegment : ip)
System.out.print(ipSegment + " " );
System.out.println( "" );
for ( byte ipSegment : ip)
{
int newIPSegment = (ipSegment < 0 ) ? 256 + ipSegment : ipSegment;
System.out.print(newIPSegment + " " );
}
}
}
import java.net. * ;
public class MyIP
{
public static void main(String[] args) throws Exception
{
InetAddress address = InetAddress.getByName( " www.csdn.net " );
byte ip[] = address.getAddress();
for ( byte ipSegment : ip)
System.out.print(ipSegment + " " );
System.out.println( "" );
for ( byte ipSegment : ip)
{
int newIPSegment = (ipSegment < 0 ) ? 256 + ipSegment : ipSegment;
System.out.print(newIPSegment + " " );
}
}
}
运行结果:
-
45
100
26
122
211 100 26 122
211 100 26 122
从上面的运行结果可以看出,第一行输出了未转换的
IP
地址,由于
www.csdn.net
的
IP
地址的第一个字节大于
127
,因此,输出了一个负数。而第二行由于将
IP
地址的每一个字节转换成了
int
类型,因此,输出了正常的
IP
地址。