PHPs ip2long and long2ip ported to Java

     In my previous post "Using Java to scan a local network for available IPs (From an old blog, the post refrenced was not ported)" I said I would post the ports of PHPs ip2long and long2ip functions at a later date.  I had intended to wait longer, but it's been kind of slow for me on the blog front the last couple weeks.  So here they are.
private static String long2ip(long l) {
                // Use bitwise bit shifting to build the new IP
    return  ((  l >> 24 )  & 0xFF) + "." +
            ((  l >> 16 )  & 0xFF) + "." +
            ((  l >> 8 )   & 0xFF) + "." +
            (   l        & 0xFF);
}
 
private static long ip2long(String addr) {
    String[] addrArray = addr.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;
}

 

Tags: