Integer IP Addresses
I 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.



Comments
No comments yet.
Leave a comment