Lamis Lamis - 1 month ago 6
Java Question

Java ip2long equivalent

Hello I'm having a database to select the IP location from>

The script was in php and I'm converting it to java but I have no idea what is the equivalent of

ip2long('127.0.0.1' ));
in java

Answer

Basically, this will convert your dotted IP address string to long.

public static Long Dot2LongIP(String dottedIP) {
    String[] addrArray = dottedIP.split("\\.");        
    long num = 0;        
    for (int i=0;i<addrArray.length;i++) {            
        int power = 3-i;            
        num += ((Integer.parseInt(addrArray[i]) % 256) * Math.pow(256,power));        
    }        
    return num;    
}