0 Replies - 4201 Views - Last Post: 28 December 2012 - 01:59 AM

#1 farrell2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 874
  • View blog
  • Posts: 2,706
  • Joined: 29-July 11

Convert IPV4 Address to Long.

Posted 28 December 2012 - 01:59 AM

Description: Simple implementation of an algorithm to convert an ipv4 address to long.
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.
        }



Is This A Good Question/Topic? 0
  • +

Page 1 of 1