简体   繁体   中英

Get next IP from a given subnet [Python]

I would like to get the next IP from the given subnet. I know how to get the IP range from notation 192.168.0.1/24 but I do not know how to get the next IP within a range. I wrote this code:

def get_next_ip(ip):
    tmp = ip.split('.')
    val = int(tmp[0]) << 24 + int(tmp[1]) << 16 + int(tmp[2]) << 8 + int(tmp[3])
    val = val + 1
    octet3 = val & 0xFF
    octet2 = (val >> 8) & 0xFF
    octet1 = (val >> 16) & 0xFF
    octet0 = (val >> 24) & 0xFF
    next_ip = str(octet0) + "." + str(octet1) + "." + str(octet2) + "." + str(octet3)
    return next_ip

And when I run print get_next_ip("192.168.0.1") it prints 0.0.0.1 instead of 192.168.0.2 . Why?

It is because of prioritization rules.
The bit shift is not only affecting each tmp[x], but the whole value before the shift operator.
First you shift int(tmp[0]) by 24
Then adds int(tmp[1])
Then shifts the total sum by 16
...

val = (int(tmp[0]) << 24) + (int(tmp[1]) << 16) + (int(tmp[2]) << 8) + int(tmp[3])  

would do it.

Your code does not respect the net mask at all. In fact it does not even use it. You parse for "." and do not care about the "/24".

All you have accomplished is parsing the IP4 Address and then adding 1 to the number ensuring the roll-over is applied.

If you want the next IP in this case the next ip+268

import ipaddress
ipaddress.ip_address('192.168.0.4') + 268
ip_str=str(ipaddress.ip_address('192.168.0.4') + 268

ip_str should now be '192.168.1.16'

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