python增加ipaddress [英] python increment ipaddress
问题描述
我想增加一个固定值的IP地址.
这正是我想要实现的目标,我有一个 IP 地址,例如 192.168.0.3
并且我想将它增加 1
这将导致 192.168.0.4
或什至是一个固定值,x
以便它将我的 IP 地址增加该数字.所以,我可以有一个像 192.168.0.3+x
这样的主机.
我只想知道此转换是否已经存在任何模块.
我尝试了 socket.inet_aton
和 socket.inet_ntoa
,但我不知道如何让它正常工作.需要一些帮助或建议.
在 Python 3 中:
<预><代码>>>>导入ip地址>>>ipaddress.ip_address('192.168.0.4') # 接受 IPv4 和 IPv6 地址IPv4Address('192.168.0.4')>>>整数(_)3232235524>>>ipaddress.ip_address('192.168.0.4') + 256IPv4Address('192.168.1.4')反过来:
<预><代码>>>>ipaddress.ip_address(3232235524)IPv4Address('192.168.0.4')>>>字符串(_)'192.168.0.4'>>>ipaddress.ip_address('192.168.0.4') -1IPv4Address('192.168.0.3')Python 2/3
您可以使用 struct
模块来解包 inet_aton()
的结果,例如,
导入结构体,socket# x.x.x.x 字符串 ->整数ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]打印(ip2int(192.168.0.4"))# ->3232235524
反过来:
int2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))打印(int2ip(3232235525))# ->192.168.0.5
I would like to increment an ip address by a fixed value.
Precisely this is what I am trying to achieve, I have an ip address say, 192.168.0.3
and I want to increment it by 1
which would result in 192.168.0.4
or even by a fixed value, x
so that it will increment my ip address by that number. so, I can have a host like 192.168.0.3+x
.
I just want to know if any modules already exist for this conversion.
I tried socket.inet_aton
and then socket.inet_ntoa
, but I don't know how to get that working properly. Need some help or advice on that.
In Python 3:
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.4') # accept both IPv4 and IPv6 addresses
IPv4Address('192.168.0.4')
>>> int(_)
3232235524
>>> ipaddress.ip_address('192.168.0.4') + 256
IPv4Address('192.168.1.4')
In reverse:
>>> ipaddress.ip_address(3232235524)
IPv4Address('192.168.0.4')
>>> str(_)
'192.168.0.4'
>>> ipaddress.ip_address('192.168.0.4') -1
IPv4Address('192.168.0.3')
Python 2/3
You could use struct
module to unpack the result of inet_aton()
e.g.,
import struct, socket
# x.x.x.x string -> integer
ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]
print(ip2int("192.168.0.4"))
# -> 3232235524
In reverse:
int2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))
print(int2ip(3232235525))
# -> 192.168.0.5
这篇关于python增加ipaddress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!