# Convert IPV4 Address to Long.

Page 1 of 1

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

### #1 farrell2k

• D.I.C Lover

Reputation: 874
• 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

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }