当前位置:网站首页>IP tools

IP tools

2022-07-07 19:39:00 Scarecrow 0.0

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;
        }
    }
}
原网站

版权声明
本文为[Scarecrow 0.0]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071729140581.html