Validate an IP Address (with Mask)

后端 未结 6 1515
一整个雨季
一整个雨季 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:19

    First you'll want to convert your IP addresses into flat ints, which will be easier to work with:

    String       s = "10.1.1.99";
    Inet4Address a = (Inet4Address) InetAddress.getByName(s);
    byte[]       b = a.getAddress();
    int          i = ((b[0] & 0xFF) << 24) |
                     ((b[1] & 0xFF) << 16) |
                     ((b[2] & 0xFF) << 8)  |
                     ((b[3] & 0xFF) << 0);
    

    Once you have your IP addresses as plain ints you can do some bit arithmetic to perform the check:

    int subnet = 0x0A010100;   // 10.1.1.0/24
    int bits   = 24;
    int ip     = 0x0A010199;   // 10.1.1.99
    
    // Create bitmask to clear out irrelevant bits. For 10.1.1.0/24 this is
    // 0xFFFFFF00 -- the first 24 bits are 1's, the last 8 are 0's.
    //
    //     -1        == 0xFFFFFFFF
    //     32 - bits == 8
    //     -1 << 8   == 0xFFFFFF00
    mask = -1 << (32 - bits)
    
    if ((subnet & mask) == (ip & mask)) {
        // IP address is in the subnet.
    }
    

提交回复
热议问题