Teneo !!!

Aaron’s blog on Networking, and Enterprise Technology

Java – IP Address to Integer and back

Posted by Aaron Paxson on December 23, 2008

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 IP.java, 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 Justin-Cook.com, 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;
    }

One Response to “Java – IP Address to Integer and back”

  1. shwetha said

    thxx uu :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>