简体   繁体   English

从给定的子网中获取下一个IP [Python]

[英]Get next IP from a given subnet [Python]

I would like to get the next IP from the given subnet. 我想从给定的子网中获取下一个IP。 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. 我知道如何从符号192.168.0.1/24获取IP范围,但我不知道如何在范围内获取下一个IP。 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 . 当我运行print get_next_ip("192.168.0.1")它将打印0.0.0.1而不是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. 移位不仅影响每个tmp [x],而且影响移位运算符之前的整个值。
First you shift int(tmp[0]) by 24 首先,将int(tmp [0])移24
Then adds int(tmp[1]) 然后添加int(tmp [1])
Then shifts the total sum by 16 然后将总和移位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". 并且不在乎“ / 24”。

All you have accomplished is parsing the IP4 Address and then adding 1 to the number ensuring the roll-over is applied. 您所要做的只是解析IP4地址,然后在数字上加1以确保应用了翻转。

If you want the next IP in this case the next ip+268 如果在这种情况下需要下一个IP,则下一个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' ip_str现在应该为“ 192.168.1.16”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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