Java – IP Address to Integer and back

Many applications store the IP Address as an integer.  This makes it easy to perform mathematical operations on it (say, adding 1024 hosts to a subnet to get min/max addresses, etc).


Currently, I am implementing IPPlan to my toolset, to help me manage all my IP’s and subnets, and make it easy for others to request IP’s.  However, I didn’t want to duplicate the IP’s in use.  I wanted my current network management system to FEED the hosts it already knows into IPPlan.


Easy, I’ll just run a daily SQL to update the IPPlan database.  The issue is, my NMS stores the IP Address as a String, and IPPlan stores it as an integer.


So, taking bits and pieces off the internet, here are a couple of cool Java methods that helped me accomplish this:


From Limewire’s, here is converting an existing Integer to String:


public static String intToIp(int i) {


return ((i >> 24 ) & 0xFF) + “.” +

((i >> 16 ) & 0xFF) + “.” +

((i >> 8 ) & 0xFF) + “.” +

( i & 0xFF);



From, here is converting an existing String to Integer:


public static Long ipToInt(String addr) {


String[] addrArray = addr.split(“\\.”);


long num = 0;

for (int i=0;i<addrArray.length;i++) {

int power = 3-i;


num += ((Integer.parseInt(addrArray[i])%256 * Math.pow(256,power)));


return num;



Share This Page : Share on TwitterShare on FacebookShare on GooglePlusShare on PinterestShare on Linkedin