给定一个IP地址(例如192.168.0.1),如何在Python中检查它是否在网络中(例如192.168.0.0/24)?
Python中是否有用于IP地址操作的通用工具?诸如主机查找,将IP地址添加到int,将网络地址与netmask转换为int之类的东西?希望可以在标准Python库中找到2.5。
本文显示您可以使用socket和struct模块完成此操作,而无需付出太多额外的努力。我在文章中添加了一些内容,如下所示:
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