2015-02-26

[Java] ipToLong 與 longToIp

public class IpToLong {

    public static long ipToLong(String ip) {
        long result = 0;
        String[] numbers = (ip + ".0.0.0").split("\\.");

        for (int i = 0; i < 4; i++) {
            result = result << 8;
            result |= Long.parseLong(numbers[i]) & 0xFF;
        }

        return result;
    }


    public static String longToIp(long ip) {
        return (ip >> 24 & 0xFF) + "." +
               (ip >> 16 & 0xFF) + "." +
               (ip >> 8 & 0xFF) + "." +
               (ip & 0xFF);
    }



    public static void main(String[] args) {

        String[] testList = {
            "0.0.0.0",
            "255.255.255.255",
            "192.168.1.2"
        };

        for (String ip : testList) {
            long ipNum = ipToLong(ip);
            System.out.printf(
                "%s | %s | %s\n", ip, longToIp(ipNum), ipNum
            );
        }
    }
}

Output:
0.0.0.0 | 0.0.0.0 | 0
255.255.255.255 | 255.255.255.255 | 4294967295
192.168.1.2 | 192.168.1.2 | 3232235778

0 回應: