Check whether the ipAddress is in private range

前端 未结 4 485
执笔经年
执笔经年 2021-02-07 06:43

How would I check to see whether the ip address is in private category ?

    if(isPrivateIPAddress(ipAddress)) {
                


        
4条回答
  •  离开以前
    2021-02-07 07:07

    First of all, Private networks can use IPv4 addresses anywhere in the following ranges:

    • a) 192.168.0.0 - 192.168.255.255 (65,536 IP addresses)
    • b) 172.16.0.0 - 172.31.255.255 (1,048,576 IP addresses)
    • c) 10.0.0.0 - 10.255.255.255 (16,777,216 IP addresses)

    As we can see from method isSiteLocalAddress in Inet4Address.java :

     public boolean isSiteLocalAddress() {
        // refer to RFC 1918
        // 10/8 prefix
        // 172.16/12 prefix
        // 192.168/16 prefix
        int address = holder().getAddress();
        return (((address >>> 24) & 0xFF) == 10)
            || ((((address >>> 24) & 0xFF) == 172)
                && (((address >>> 16) & 0xF0) == 16))
            || ((((address >>> 24) & 0xFF) == 192)
                && (((address >>> 16) & 0xFF) == 168));
    }
    

    So case b) 172.16.0.0 - 172.31.255.255 (1,048,576 IP addresses) is not satisfied. But you can easily write you own version of how to tell whether a address is private address.Here is my version:

    import com.google.common.net.InetAddresses;
    
    private static boolean isPrivateV4Address(String ip) {
        int address = InetAddresses.coerceToInteger(InetAddresses.forString(ip));
        return (((address >>> 24) & 0xFF) == 10)
                || ((((address >>> 24) & 0xFF) == 172) 
                  && ((address >>> 16) & 0xFF) >= 16 
                  && ((address >>> 16) & 0xFF) <= 31)
                || ((((address >>> 24) & 0xFF) == 192) 
                  && (((address >>> 16) & 0xFF) == 168));
    }
    

提交回复
热议问题