Java – INET_NTOA and INET_ATON in Java

ip addressjava

I use Java (with Spring framework) and want to convert between numeric representations of IPv4 addresses (e.g. 2130706433) and their textual counterparts (e.g. 127.0.0.1). Often, methods for doing this are supplied in programming languages (they're usually called INET_NTOA and INET_ATON respectively) but I can't find it in Java.

Anybody knows what they're called or how to implement them?

Best Answer

Look at InetAddress in the javadocs. These functions are not directly supported by the Standard API but you can extract both representations using this class. A small example:

    InetAddress address = InetAddress.getLocalHost();
    byte[] byteAddress = address.getAddress();
    System.out.println(Arrays.toString(byteAddress));
    System.out.println(address.getHostAddress());

(Keep in mind that bytes are signed.)


If you have long-s than yo can use ByteBuffer, for fast and comfortable coversion. Methods: putLong() then array().