The GetAddress method is similar to gethostaddress, where the only difference is that the Gethostaddress method returns an IP address in the form of a string, and the GetAddress method returns an IP address in the form of a byte array. the GetAddress method is defined as follows:
Public byte[] GetAddress ()
The byte array returned by this method is signed. The value range of byte type in Java is -128?127. If a byte of the returned IP address is an integer greater than 127, a negative number is in the byte array. Because there is no unsigned byte type in Java, you must use an int or long type to display the normal IP address. The following code shows how to use GetAddress to return an IP address and how to convert an IP address into a positive integer.
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&NBSP;IPSEGMENT&NBSP;:&NBSP;IP) system.out.print (ipSegment + " "); system.out.println (""); for (BYTE&NBSP;IPSEGMENT&NBSP;:&NBSP;IP) { int newipsegment = (ipsegment < 0) &NBSP;?&NBSP;256&NBSP;+&NBSP;IPSEGMENT&NBSP;:&NBsp;ipsegment; system.out.print (newIPSegment + " "); } }}
Operation Result:
-45 100 26 122 211 100 26 122
As can be seen from the running results above, the first line outputs an IP address that is not converted, because the first byte of the IP address of the www.csdn.net is greater than 127, so a negative number is output. The second line, by converting each byte of the IP address to the int type, outputs a normal IP address.
Java network programming from getting started to mastering (8): Obtaining an IP address using the GetAddress method