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?
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With