The getaddress method is similar to the gethostaddress method. The only difference between the gethostaddress method and gethostaddress method is that the gethostaddress method returns an IP address in the form of a string, while 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. In Java, the value range of the byte type is-128 ~ 127. If a byte of the returned IP address is an integer greater than 127, It is a negative number in the byte array. Because Java does not have an unsigned byte type, Int or long type must be used to display normal IP addresses. The following code demonstrates how to use getaddress to return IP addresses and convert IP addresses into integers.
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 + " "); } }}
Running result:
-45 100 26 122 211 100 26 122
From the preceding running results, we can see that the first line outputs unconverted IP addresses. Because the first byte of the IP address of www.csdn.net is greater than 127, a negative number is output. The second line outputs a normal IP address because each byte of the IP address is converted to the int type.