The formula for converting an IPV4 address to its value in long, is as follows:
(first octet * 256^3) + (second octet * 256^2) + (third octet * 256) + (fourth octet)
public static Long ipToLong(String ip) throws IllegalArgumentException { //the exception we're going to throw IF you input something invalid. IllegalArgumentException ex = new IllegalArgumentException("Invalid IP address " + ip); //create a Strin array of each octet, using "." as the delimiter. String[] octets = ip.split(Pattern.quote(".")); //if the array is != 4, you did input an invalid IP address, so just throw the IllegalArgumentException. if (octets.length == 4) { //Lopp through the arry and check to make sure you didn't input an octet greater than 255, thus invalidating the IP. for (String s : octets) { if (Integer.parseInt(s) > 255) //You input an invalid address, so throw ex. throw ex; } //everything is good, so we do our calculations and return our long. long oct1 = Integer.parseInt(octets[0]) * (long)Math.pow(256,3); long oct2 = Integer.parseInt(octets[1]) * (long)Math.pow(256,2); long oct3 = Integer.parseInt(octets[2]) * 256; long oct4 = Integer.parseInt(octets[3]); return oct1 + oct2 + oct3 + oct4; } else throw ex; //You input and invalid address, because it was < or > 4 octets, making your String[] < or > 4. }
Edited by Alexander, 13 April 2012 - 10:34 PM.
Corrected formatting issues