IP 工具类

public class IPUtils {
    public IPUtils() {
    }

    public static String convertIPToString(long ipLong) {
        if (ipLong < 0L) {
            ipLong += 4294967296L;
        }

        StringBuilder builder = new StringBuilder(15);
        builder.append(ipLong >> 24);
        builder.append('.');
        builder.append((ipLong & 16777215L) >> 16);
        builder.append('.');
        builder.append((ipLong & 65535L) >> 8);
        builder.append('.');
        builder.append(ipLong & 255L);
        return builder.toString();
    }

    public static Long convertIPToLong(String ipAddr, Long defaultValue) {
        try {
            return convertIPToLong(ipAddr);
        } catch (IllegalArgumentException var3) {
            return defaultValue;
        }
    }

    public static long convertIPToLong(String ipAddr) throws IllegalArgumentException {
        if (ipAddr != null && isIPAddr(ipAddr)) {
            String[] ips = ipAddr.split("\\.");
            long ipLong = 0L;
            ipLong += Long.parseLong(ips[0]) << 24;
            ipLong += Long.parseLong(ips[1]) << 16;
            ipLong += Long.parseLong(ips[2]) << 8;
            ipLong += Long.parseLong(ips[3]);
            return ipLong;
        } else {
            throw new IllegalArgumentException("`" + ipAddr + "` is not a valid IP address!");
        }
    }

    public static Integer convertIPToInt(String ipAddr, Integer defaultValue) {
        try {
            return convertIPToInt(ipAddr);
        } catch (IllegalArgumentException var3) {
            return defaultValue;
        }
    }

    public static int convertIPToInt(String ipAddr) {
        long ipVal = convertIPToLong(ipAddr);
        if (ipVal > 2147483647L) {
            ipVal -= 4294967296L;
        }

        return Long.valueOf(ipVal).intValue();
    }

    public static boolean isIPAddr(String addr) {
        if (addr != null && addr.trim().length() != 0) {
            String[] ips = addr.split("\\.");
            if (ips.length != 4) {
                return false;
            } else {
                try {
                    int ipa = Integer.parseInt(ips[0]);
                    int ipb = Integer.parseInt(ips[1]);
                    int ipc = Integer.parseInt(ips[2]);
                    int ipd = Integer.parseInt(ips[3]);
                    return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0 && ipc <= 255 && ipd >= 0 && ipd <= 255;
                } catch (NumberFormatException var6) {
                    return false;
                }
            }
        } else {
            return false;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值