Integer IP Addresses
04 Mar 2009I know that every couple of years I need the snippet of code that helps me convert the integer version of an IP address back and forth to a string. You would think that after all this time I’d be able to write it blind.
public static String convertIntegerToIp(long ip) {
StringBuffer buf = new StringBuffer();
buf.append(((ip >> 24 ) & 0xFF)).append(".")
.append(((ip >> 16 ) & 0xFF)).append(".")
.append(((ip >> 8 ) & 0xFF)).append(".")
.append(( ip & 0xFF));
return buf.toString();
}
public static long convertStringToIntegerIp(String ip) {
String[] parts = ip.split("\\.");
return (Long.valueOf(parts[0]) << 24) +
(Long.valueOf(parts[1]) << 16) +
(Long.valueOf(parts[2]) << 8) +
(Long.valueOf(parts[3]));
}
In C/C++ you can use an unsigned int instead of a long but in java there are no unsigned types and while I know that you can still do this calculation using a signed integer just as well in java, when you print out the address for visual inspection you will get a negative number and it won’t match the c++ printout so I’ve chosen to use a long to store the values.
Enjoy.