Check whether the ipAddress is in private range

前端 未结 4 484
执笔经年
执笔经年 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:08

    I use this:

    public boolean isPrivateIP(String ipAddress) {
            boolean isValid = false;
    
            if (ipAddress != null && !ipAddress.isEmpty()) {
                String[] ip = ipAddress.split("\\.");
                short[] ipNumber = new short[] { 
                        Short.parseShort(ip[0]), 
                        Short.parseShort(ip[1]), 
                        Short.parseShort(ip[2]),
                        Short.parseShort(ip[3])
                    };
    
                if (ipNumber[0] == 10) { // Class A
                    isValid = true;
                } else if (ipNumber[0] == 172 && (ipNumber[1] >= 16 && ipNumber[1] <= 31)) { // Class B
                    isValid = true;
                } else if (ipNumber[0] == 192 && ipNumber[1] == 168) { // Class C
                    isValid = true;
                }
            }
    
            return isValid;
        }
    

提交回复
热议问题