How to check if an IP address is from a particular network/netmask in Java?

后端 未结 7 2192
北恋
北恋 2020-11-29 23:33

I need to determine if given IP address is from some special network in order to authenticate automatically.

7条回答
  •  佛祖请我去吃肉
    2020-11-29 23:44

    To check An IP in a subnet, I used isInRange method in SubnetUtils class. But this method have a bug that if your subnet was X, every IP address that lower than X, isInRange return true. For example if your subnet was 10.10.30.0/24 and you want to check 10.10.20.5, this method return true. To deal with this bug I used below code.

    public static void main(String[] args){
        String list = "10.10.20.0/24";
        String IP1 = "10.10.20.5";
        String IP2 = "10.10.30.5";
        SubnetUtils  subnet = new SubnetUtils(list);
        SubnetUtils.SubnetInfo subnetInfo = subnet.getInfo();
        if(MyisInRange(subnetInfo , IP1) == true)
           System.out.println("True");
        else 
           System.out.println("False");
        if(MyisInRange(subnetInfo , IP2) == true)
           System.out.println("True");
        else
           System.out.println("False");
    }
    
    private boolean MyisInRange(SubnetUtils.SubnetInfo info, String Addr )
    {
        int address = info.asInteger( Addr );
        int low = info.asInteger( info.getLowAddress() );
        int high = info.asInteger( info.getHighAddress() );
        return low <= address && address <= high;
    }
    

提交回复
热议问题