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.

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.");    }  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may