How to check if an IP address is within a particular subnet

后端 未结 7 1456
深忆病人
深忆病人 2020-12-01 12:15

I have a subnet in the format 10.132.0.0/20 and an IP address from the ASP.Net request object.

Is there a .NET framework function to check to see if the IP address i

7条回答
  •  情书的邮戳
    2020-12-01 12:25

    Bit manipulation works. Stuff the IP into a 32-bits unsigned integer, do the same with the subnet's address, &-mask both with 0xFFFFFFFF << (32-20) and compare:

    unsigned int net = ..., ip = ...;
    int network_bits = 20;
    unsigned int mask = 0xFFFFFFFF << (32 - network_bits);
    if ((net & mask) == (ip & mask)) {
      // ...
    }
    

提交回复
热议问题