getHostName()
There are no corresponding setHostName() and setAddress() methods, which means that packages outside of java.net can’t change an InetAddress object’s fields behind its back. This makes InetAddress immutable and thus thread safe. The getHostName() method returns a String that contains the name of the host with the IP address represented by this InetAddress object. If the machine in question doesn’t have a hostname or if the security manager prevents the name from being determined, a dotted quad format of the numeric IP address is returned. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getHostName();
getCanonicalHostName()
The getCanonicalHostName() method is similar, but it’s a bit more aggressive about contacting DNS. getHostName() will only call DNS if it doesn’t think it already knows the hostname. getCanonicalHostName() calls DNS if it can, and may replace the existing cached hostname. For example:
InetAddress machine = InetAddress.getLocalHost();
String localhost = machine.getCanonicalHostName();
The getCanonicalHostName() method is particularly useful when you’re starting with a dotted quad IP address rather than the hostname.
getAddress
If you want to know the IP address of a machine (and you rarely do), then use the getAddress() method, which returns an IP address as an array of bytes in network byte order. The most significant byte (i.e., the first byte in the address’s dotted quad form) is the first byte in the array, or element zero. To be ready for IPv6 addresses, try not to assume anything about the length of this array. If you need to know the length of the array, use the array’s length field:
InetAddress me = InetAddress.getLocalHost();
byte[] address = me.getAddress();
The bytes returned are unsigned, which poses a problem. Unlike C, Java doesn’t have an unsigned byte primitive data type. Bytes with values higher than 127 are treated as negative numbers. Therefore, if you want to do anything with the bytes returned by getAddress(), you need to promote the bytes to ints and make appropriate adjusments. Here’s one way to do it:
int unsignedByte = signedByte < 0 ? signedByte + 256 : signedByte
Here, signedByte may be either positive or negative. The conditional operator ? tests whether signedByte is negative. If it is, 256 is added to signedByte to make it positive. Otherwise, it’s left alone. signedByte is automatically promoted to an int before the addition is performed, so wraparound is not a problem. One reason to look at the raw bytes of an IP address is to determine the type of the address. Test the number of bytes in the array returned by getAddress() to determine whether you’re dealing with an IPv4 or IPv6 address.