Parsing InetAddressess

You can ask InetAddress object for its host name as a string, its IP address as a string, its IP address as a byte array, and whether or not it's a multicast address. The necessary methods are:

 public boolean isMulticastAddress()
 public String getHostName()
 public byte[] getAddress()
 public String getHostAddress()

The following program prints out this information about the local host.


public class Local {

  public static void main(String[] args) {

    try {
      InetAddress me = InetAddress.getLocalHost();
      System.out.println("My name is " + me.getHostName());
      System.out.println("My address is " + me.getHostAddress());
      byte[] address = me.getAddress();
      for (int i = 0; i < address.length; i++) {
        System.out.print(address[i] + " ");
    catch (UnknownHostException e) {
      System.err.println("Could not determine local address.");
      System.err.println("Perhaps the network is down?");

My name is
My address is
-88 100 -53 -22 

Note that the bytes returned by getAddress() are signed even though the convention is to use unsigned bytes in a dotted quad address.

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
Last Modified April 15, 1999