简体   繁体   中英

Calculate netmask from list of IP's

I have a list of IPv4 addresses that are all on the same network. I would like to calculate a netmask for that network given the list of IP's.

List:

192.168.2.2
192.168.2.3
192.168.2.4

Resulting netmask: 255.255.255.0

Current algorithm: If octets differ place a 0 in that netmask position, else place 255 .

prev_ip = None
current_netmask = [255,255,255,255]
for ip in ip_list:
  if prev_ip != None:
    for i in range(0,4):
      if ip.split('.')[i] != prev_ip.split('.')[i]:
        current_netmask[i] = 0
  prev_ip = ip    

My issue is that this netmask is not always correct, and I know other netmasks are possible (other than ones comprised of 0's and 255's)

I think this will work. Converts addresses to integers, starts with a mask of all 1s and will progressively zero increasing bits starting at the least significant while the IPs differ when bitwise and-ed with the mask. (Each new IP only needs to be compared with one of the IPs already considered, because by that stage the mask already reflects the comparison with the other IPs considered, hence the line with vals[0] .) Finally it converts the mask back to dotted quad representation.

def to_int(ip):
    bytes = [int(s) for s in ip.split(".")]
    return sum(val<<(8*i) for i, val in enumerate(reversed(bytes)))

def from_int(val):
    r = []
    while val:
        r.append(val & 0xFF)
        val >>= 8
    if len(r) < 4:
        r.extend([0] * (4-len(r)))
    return ".".join(map(str, reversed(r)))

def get_mask(ips):
    vals = [to_int(ip) for ip in ips]
    mask = 0xFFFFFFFF
    bit = 1
    for val in vals[1:]:
        while vals[0] & mask != val & mask:
            mask &= ~bit
            bit <<= 1
    return from_int(mask)

ips = ["192.168.2.2", "192.168.2.3", "192.168.2.4"]
print(get_mask(ips))

gives:

255.255.255.248

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM