Validate an IP Address (with Mask)

后端 未结 6 1512
一整个雨季
一整个雨季 2021-02-01 09:52

I have ip addresses and a mask such as 10.1.1.1/32. I would like to check if 10.1.1.1 is inside that range. Is there a library or utility that would do

6条回答
  •  再見小時候
    2021-02-01 10:30

    This is just a few lines of code with the open-source IPAddress Java library. Disclaimer: I am the project manager of the IPAddress library.

    String subnetStr = "10.1.1.1/24";
    String addrStr = "10.1.1.1";
    IPAddress subnetAddress = new IPAddressString(subnetStr).getAddress();
    IPAddress subnet = subnetAddress.toPrefixBlock();
    IPAddress testAddress = new IPAddressString(addrStr).getAddress();
    boolean result = subnet.contains(testAddress);
    System.out.println(subnetAddress + " is in subnet " + subnet + " and " +
                (result ? "contains" : "does not contain") + " address " + testAddress);
    

    Output:

    10.1.1.1/24 is in subnet 10.1.1.0/24 and contains address 10.1.1.1
    

提交回复
热议问题