Calculate IP range by subnet mask

前端 未结 4 1576
傲寒
傲寒 2020-12-31 20:12

If I have a subnet mask e.g. 255.255.255.0 and an ip address 192.168.1.5, is there an easy way to determine all the possible ip addresses within th

4条回答
  •  执笔经年
    2020-12-31 20:20

    Good call. Don't use extra libraries for that. It's quite simple. This is how I do it:

    public static uint[] GetIpRange(string ip, IPAddress subnet)
    {
        uint ip2 = Utils.IPv4ToUInt(ip);
        uint sub = Utils.IPv4ToUInt(subnet);
    
        uint first = ip2 & sub;
        uint last = first | (0xffffffff & ~sub);
    
        return new uint[] { first, last };
    }
    

    Note:
    You'll need to do some more work converting IPs to uint and back (should be easy enough). Then you can iterate all IPs with a simple for-loop between first and last.

    Something like this (not tested):

    byte[] bytes = subnet.GetAddressBytes();
    uint sub = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
    
    IPAddress ip1 = IPAddress.Parse(ip);
    bytes = ip1.GetAddressBytes();
    uint ip2 = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
    

提交回复
热议问题