给定一个IP地址(例如192.168.0.1),如何在Python中检查它是否在网络中(例如192.168.0.0/24)?
Python中是否有用于IP地址操作的通用工具?诸如主机查找,将IP地址添加到int,将网络地址与netmask转换为int之类的东西?希望可以在标准Python库中找到2.5。
最佳答案
This article显示您可以使用 socket
和 struct
模块来完成此任务,而无需花费太多精力。我在文章中添加了一些内容,如下所示:
import socket,struct
def makeMask(n):
"return a mask of n bits as a long integer"
return (2L<<n-1) - 1
def dottedQuadToNum(ip):
"convert decimal dotted quad string to long integer"
return struct.unpack('L',socket.inet_aton(ip))[0]
def networkMask(ip,bits):
"Convert a network address to a long integer"
return dottedQuadToNum(ip) & makeMask(bits)
def addressInNetwork(ip,net):
"Is an address in a network"
return ip & net == net
address = dottedQuadToNum("192.168.1.1")
networka = networkMask("10.0.0.0",24)
networkb = networkMask("192.168.0.0",24)
print (address,networka,networkb)
print addressInNetwork(address,networka)
print addressInNetwork(address,networkb)
输出:
False
True
如果您只想要一个采用字符串的函数,则它将看起来像这样:
import socket,struct
def addressInNetwork(ip,net):
"Is an address in a network"
ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
netaddr,bits = net.split('/')
netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
return ipaddr & netmask == netmask