devxlogo

Converting IP Address Formats

Converting IP Address Formats

Question:
Is there a Java equivalent class or method for the Unix Internet address manipulation routines like inet_ntoa()?

Answer:
Java does not have direct analogs for the inet functions that originally appeared in the BSD 4.3 C library, but still supports the equivalent functionality. All Internet address manipulation in Java is handled by the InetAddress class in the java.net package. InetAddress instances cannot be created directly by using the newoperator and invoking a constructor. They can only be created by calling one of the InetAddress static methods that perform host lookups: getLocalHost, getByName, and getAllByName. Once you have created an InetAddress object, you can obtain the hostname, the string representation of the IP address, or the raw byte representation of the IP address in network byte order, by invoking the getHostName, getAddress, and getHostAddress methods respectively.

All classes and their methods that require IP addresses deal with InetAddress objects. Therefore, the inet_ntoa() C function you refer to does not quite have a direct analog. Even though calling getHostAddress provides similar functionality, if you only have the byte representation of an IP address, there is no canned way of turning it into an InetAddress instance. It is, however, easy to write a method that will do this for you as demonstrated in thelisting. The rawToInetString method performs essentially the same task as inet_ntoa, and the rawToInetAddress utilizes the result to create an InetAddress instance. The main program merely tests the methods by taking a list of hostnames as arguments, looking up their addresses, and using the resulting InetAddress objects to verify the rawToString and rawToInetAddress methods.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email

import java.net.*;public final class RawIPToString {  // Mimics BSD Unix's inet_ntoa(), assumes address is in network byte order  // and that the array has 4 entries.  public static String rawToString(byte[] address) {    int octet, count = 0;    StringBuffer result = new StringBuffer();    while(true) {      octet = address[count] & 0xff;      result.append(octet);      if(count++ >= 3)	break;      result.append('.');    }    return result.toString();  }  public static InetAddress rawToInetAddress(byte[] address)    throws UnknownHostException  {    return InetAddress.getByName(rawToString(address));  }  public static void main(String[] args) {    int host;    InetAddress address, fabricatedAddress;    if(args.length < 1) {      System.err.println("Usage: RawIPToString hostname1 [hostname2] ...");      System.exit(1);    }    for(host = 0; host < args.length; ++host) {      try {	address = InetAddress.getByName(args[host]);      } catch(UnknownHostException e) {	System.err.println("Unknown host: " + args[host]);	continue;      }      System.out.println("getAddress() : " + args[host] + " is " +			 address.getHostAddress());      System.out.println("rawToString(): " + args[host] + " is " +			 rawToString(address.getAddress()));      try {	fabricatedAddress = rawToInetAddress(address.getAddress());      } catch(UnknownHostException e) {	System.err.println(		   "Could not fabricate an address with rawToInetAddress()");	continue;      }      if(fabricatedAddress.equals(address))	System.out.println("Fabricated and original addresses are equal.");      else	System.out.println(		   "Error: Fabricated and original addresses are NOT equal.");    }  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist