GetAddressMethod andGetHostAddressSimilarly, the only difference between them isGetHostAddressThe method returns a string.IPAddress, andGetAddressThe method returnsByteArray formatIPAddress.GetAddressThe method is defined as follows:
Public Byte[] GetAddress ()This method returnsByteArrays are signed. InJavaMediumByteThe value range of the type is-128〜127. IfIPA byte of the address is greater127InByteThe array is a negative number. BecauseJavaIs not signedByteType.IPAddress, which must be usedIntOrLongType. The following codeDemonstrate how to useGetAddressReturnIPAddress, and howIPThe address is converted to an integer.
PackageMynet;
ImportJava.net.*;
Public ClassMyIP
{
Public Static VoidMain (String [] args)ThrowsException
{
InetAddress address=InetAddress. getByName ("Www.csdn.net");
ByteIp []=Address. getAddress ();
For(ByteIpSegment: ip)
System. out. print (ipSegment+ " ");
System. out. println ("");
For(ByteIpSegment: ip)
{
IntNewIPSegment=(IpSegment< 0)? 256 +IpSegment: ipSegment;
System. out. print (newIPSegment+ " ");
}
}
}
Running result:
- 45 100 26 122
211 100 26 122
From the preceding running results, we can see that the first line outputs unconvertedIPAddress, becauseWww.csdn.netOfIPThe first byte of the address is greater127Therefore, a negative number is output. The second lineIPEach byte of the address is converted