Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INET_NTOA and INET_ATON in Java?

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?

like image 896
Gruber Avatar asked Feb 03 '12 13:02

Gruber


2 Answers

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().

like image 82
zeller Avatar answered Oct 07 '22 07:10

zeller


Here's what I wrote myself to get a numeric representation of a textual IPv4 address:

public static Long ipAsNumeric(String ipAsString) {
    String[] segments = ipAsString.split("\\.");
    return (long) (Long.parseLong(segments[0]) * 16777216L
       + Long.parseLong(segments[1]) * 65536L
       + Long.parseLong(segments[2]) * 256L + 
         Long.parseLong(segments[3]));
}

Of course, this assumes the IPv4 address is given on a valid format.

like image 24
Gruber Avatar answered Oct 07 '22 06:10

Gruber