IPUtils

1.ip在数据库中存储(INT UNSIGNED or BIGINT)
select INET_ATON('101.81.88.85') FROM DUAL; ip to long
select INET_NTOA('1699829845') FROM DUAL; long to ip
2.工具类
public final class IPUtils {

    private IPUtils() { }

    public static long ip2Long(String ipAddress) {
        if (StringUtils.isBlank(ipAddress)) {
            return 0;
        }
        long result = 0;
        String[] ipAddressInArray = ipAddress.split("\\.");
        for (int i = 3; i >= 0; i --) {
            long ip = Long.parseLong(ipAddressInArray[3 - i]);
            result |= ip << (i * 8);
        }
        return result;
    }

    public static String long2Ip(long ip) {
        StringBuilder sb = new StringBuilder(15);
        for (int i = 0; i < 4; i++) {
            sb.insert(0, Long.toString(ip & 0xff));
            if (i < 3) {
                sb.insert(0, '.');
            }
            ip = ip >> 8;
        }
        return sb.toString();
    }
}
3.测试
public static void main(String[] args) {
    long longIP = ip2Long("255.102.11.10");
    System.out.println(longIP);
    System.out.println(long2Ip(longIP));
}

你可能感兴趣的:(IPUtils)