IP转int Java代码实现 - TFdream/blog GitHub Wiki

IP地址刚好32位,与java中的int范围匹配,转换代码如下:


/**
 * @author Ricky Fung<br/>
 * Created on 2018-04-23<br/>
 */
public class IpUtils {

    /**
     * IP to long
     * @param ip
     * @return
     */
    public static long ip2Long(String ip) {
        String[] arr = toStringArray(ip,"\\.");
        long result = 0;
        for (String part: arr) {
            // shift the previously parsed bits over by 1 byte
            result = result << 8;
            // set the low order bits to the current octet
            result |= Integer.parseInt(part);
        }
        return result;
    }

    /**
     * long to ip
     * @param ip
     * @return
     */
    public static String long2Ip(long ip) {
        return int2Ip((int)ip);
    }

    /**
     * IP to int
     * @param ip
     * @return
     */
    public static int ip2Int(String ip) {
        String[] arr = toStringArray(ip,"\\.");
        int result = 0;
        for (String part: arr) {
            // shift the previously parsed bits over by 1 byte
            result = result << 8;
            // set the low order bits to the current octet
            result |= Integer.parseInt(part);
        }
        return result;
    }

    /**
     * int to IP
     * @param ip
     * @return
     */
    public static String int2Ip(int ip) {
        byte[] arr = toByteArray(ip);
        StringBuilder sb = new StringBuilder(15);
        sb.append((int) arr[0] & 0xFF).append(".");
        sb.append((int) arr[1] & 0xFF).append(".");
        sb.append((int) arr[2] & 0xFF).append(".");
        sb.append((int) arr[3] & 0xFF);
        return sb.toString();
    }

    public static byte[] toByteArray(int value) {
        return new byte[] {
                (byte)(value >> 24),
                (byte)(value >> 16),
                (byte)(value >> 8),
                (byte)value};
    }

    public static String[] toStringArray(String str, String separator) {
        return str.split(separator);
    }
}

测试代码:

/**
 * @author Ricky Fung<br/>
 * Created on 2018-04-23<br/>
 */
public class AppTest {

    @Test
    public void testLongIp() {
        String ip = "226.141.128.255";
        long intIp = IpUtils.ip2Long(ip);
        System.out.println(intIp);

        System.out.println(IpUtils.long2Ip(intIp));
    }

    @Test
    public void testIntIp() {
        String ip = "226.141.10.255";
        int intIp = IpUtils.ip2Int(ip);
        System.out.println(intIp);
        System.out.println(IpUtils.int2Ip(intIp));
    }
}
⚠️ **GitHub.com Fallback** ⚠️