Wednesday, 14 December 2016

How to Convert IPv4 address to Long in Java?

While working with an application, there is a requirement of getting the long value of user IP address and I needed to convert the long value to IP address. To fulfill this requirement, I wrote one class IPConversion with two methods - ipToLong and longToIP.

ipToLong method takes the user IPv4 address as input in the form of String value and returns the long value of the IP.

And longToIP method takes the long value of IPv4 address as input and return the IP address.

I have written one Exception class IPInvalidFormatException, which will be called if the format of IP address is not valid.

Now let us see the example -

class IPInvalidFormatException extends Exception{

IPInvalidFormatException(){
System.out.println("Invalid IP Format Exception");
}

@Override
public String toString() {
return "Invalid IP Format";
}

}

public class IPConversion {

 // Method to convert IPv4 to Long
 public long ipToLong(String addr) throws IPInvalidFormatException {
String[] addrArray = addr.split("\\.");

long num = 0;
for (int i = 0; i < addrArray.length; i++) {
if(addrArray.length != 4){
throw new IPInvalidFormatException();
}
int power = 3 - i;

num += ((Integer.parseInt(addrArray[i]) % 256 * Math
.pow(256, power)));
}
return num;
}

 // Method to convert Long to IPv4
 public String longToIP(long l) {
return ((l >> 24) & 0xFF) + "." + ((l >> 16) & 0xFF) + "."
+ ((l >> 8) & 0xFF) + "." + (l & 0xFF);
}

public static void main(String args[]) throws IPInvalidFormatException{

IPConversion ip = new IPConversion();
System.out.println(ip.ipToLong("10.138.161.136"));
System.out.println(ip.longToIP(176857480));
System.out.println(ip.ipToLong("10.138.161.136.0"));
}
}

Output -

176857480
10.138.161.136
Invalid IP Format Exception
Exception in thread "main" Invalid IP Format
at com.anjan.test.IPConversion.ipToLong(IPConversion.java:24)
at com.anjan.test.IPConversion.main(IPConversion.java:44)

No comments:

Post a Comment