简体   繁体   中英

Increment a IP address using subnet Mask

I'm trying to increment an IP based on the subnet Mask. is there a way to do it? i was able to increment IP address with intergers but not with Subnet Mask. I went the documentation of the IPAddress Module but could not figure out a way to do it. is there a way to do that.?

>>> a
IPv4Address('192.168.1.1')
>>> a + 256
IPv4Address('192.168.2.1')
>>>
>>>
>>>
>>> sub_incr = '0.0.1.0'
>>> a + ipaddress.IPv4Address(sub_incr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'IPv4Address' and 'IPv4Address'
>>> ```

Is there a way to do it?

In your case, you can simply convert your "netmask" to int and add it to the IP:

print(IPv4Address('192.168.1.1') + int(ipaddress.IPv4Address('0.0.1.0')))

If you have a netmask in CIDR notation (for example 192.168.1.1/24), you can use a simple bitshift:

def increment(ip, mask):
    return ip + (1 << (32 - mask))

print(increment(ipaddress.IPv4Address('192.168.1.1'), 24))

If you have spelled-out netmask (eg 255.255.255.0) you can use IPv4Network to convert it to CIDR:

print(IPv4Network("192.168.1.1/255.255.255.0", strict=False).prefixlen) 

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