Python - ip< - >子网匹配? [英] Python - ip <-> subnet match?
问题描述
可能重复:
如何检查ip是否在python中的网络中
在python中将子网与ip地址匹配的简单方法是什么,如果ip地址在子网中,我可以选择它吗? / p>
提前致谢。
在Python 3.3+中,你可以使用 ipaddress 模块:
>>> import ipaddress
>>> ipaddress.ip_address('192.0.43.10')in ipaddress.ip_network('192.0.0.0/16')
True
如果您的Python安装时间早于3.3,则可以使用此backport 。
如果您想以这种方式评估批次的IP地址,那么'' ll可能想要预先计算网络掩码,比如
n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)
然后,对于每个地址,使用
a = int(ipaddress.ip_address('192.0.43.10)之一计算二进制表示'))
a = struct.unpack('!I',socket.inet_pton(socket.AF_INET,'192.0.43.10'))[0]
a = struct.unpack('!I',socket .inet_aton('192.0.43.10'))[0] #IPv4只
最后,你可以简单地说检查:
in_network =(a& mask)== netw
Possible Duplicate:
How can I check if an ip is in a network in python
What is the easy way to match subnet to an ip address in python, so that if the ip address is in the subnet I can choose it?
Thanks in advance.
In Python 3.3+, you can use ipaddress module:
>>> import ipaddress
>>> ipaddress.ip_address('192.0.43.10') in ipaddress.ip_network('192.0.0.0/16')
True
If your Python installation is older than 3.3, you can use this backport.
If you want to evaluate a lot of IP addresses this way, you'll probably want to calculate the netmask upfront, like
n = ipaddress.ip_network('192.0.0.0/16')
netw = int(n.network_address)
mask = int(n.netmask)
Then, for each address, calculate the binary representation with one of
a = int(ipaddress.ip_address('192.0.43.10'))
a = struct.unpack('!I', socket.inet_pton(socket.AF_INET, '192.0.43.10'))[0]
a = struct.unpack('!I', socket.inet_aton('192.0.43.10'))[0] # IPv4 only
Finally, you can simply check:
in_network = (a & mask) == netw
这篇关于Python - ip< - >子网匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!