Thursday, May 11, 2006

Convert IP from String to long

I wrote this for work, but we didn't need it. So in case someone else needs a java routine to convert an ip address from String to long and back again (and it needs to be compatible w/ the method used by Unix), here it is....


package com.td.wss.docs.util;

import java.util.StringTokenizer;

public class IpUtil
{
public static long ipToLong(String ip)
{
StringTokenizer thisTok=new StringTokenizer(ip, ".", false);

long outLong=0;

outLong += Long.parseLong((String)thisTok.nextElement()) << 24;
outLong += Long.parseLong((String)thisTok.nextElement()) << 16;
outLong += Long.parseLong((String)thisTok.nextElement()) << 8;
outLong += Long.parseLong((String)thisTok.nextElement());

return outLong;
}


public static String longToIp(long ip)
{
String ip0, ip1, ip2, ip3;

ip3 = String.valueOf((ip >> 24));
ip2 = String.valueOf((ip & 0x00FF0000) >> 16);
ip1 = String.valueOf((ip & 0x0000FF00) >> 8);
ip0 = String.valueOf((ip & 0x000000FF));

return ip3 + "." +
ip2 + "." +
ip1 + "." +
ip0;
}

/**
* Results should match http://www.t1shopper.com/tools/calculate/ip-subnet/
* @param args
*/
public static void main(String[] args)
{
// Test1
runTest("255.255.255.255");

// Test2
runTest("127.0.0.1");

// Test3
runTest("0.0.0.0");

// Test4
runTest("12.33.158.6");

}

private static void runTest(String ip)
{
long result = ipToLong(ip);
System.out.println("ip=" + ip + " as long " + result);

String ipStr = longToIp(result);
System.out.println("ip=" + result + " as ip " + ipStr);
}

}