There is a usual ip and a list of ip ranges of the form "2.0.0.0 - 2.15.255.255". How to determine if ip is in the range?
2 answers
I would do something like that, translate it into a number, and then compare it as usual.
def IP2Int(ip): o = map(int, ip.split('.')) return 0x1000000 * o[0] + 0x10000 * o[1] + 0x100 * o[2] + o[3] MinD = IP2Int('2.0.0.0') MaxD = IP2Int('2.15.255.255') TGood= IP2Int('2.10.255.255') TBad = IP2Int('3.0.0.0') print MinD<= TGood and TGood<=MaxD print MinD<= TBad and TBad<=MaxD
- oneI would write constants in hexadecimal form, then it would be clear that these are actually round numbers, and not some kind of magic constants. It would be even better to use shift instead of multiplication. - insolor
- @insolor so? I can't believe it from my phone) - pavel
- Yes, as an option. - insolor
|
>>> from ipaddress import ip_address >>> netaddr, broadcast = map(ip_address, ["2.0.0.0", "2.15.255.255"]) >>> netaddr <= ip_address("2.1.0.0") <= broadcast True >>> netaddr <= ip_address("3.1.0.0") <= broadcast False
Or:
>>> import ipaddress >>> ipaddress.summarize_address_range(netaddr, broadcast) [IPv4Network('2.0.0.0/12')] >>> from ipaddress import ip_network >>> ip_address('2.1.0.0') in ip_network('2.0.0.0/12') True >>> ip_address('3.1.0.0') in ip_network('2.0.0.0/12') False
>>> import socket >>> import struct >>> ip2int = lambda ip: struct.unpack('!I', socket.inet_aton(ip))[0] >>> netaddr, broadcast = map(ip2int, ["2.0.0.0", "2.15.255.255"]) >>> netaddr <= ip2int("2.1.0.0") <= broadcast True >>> netaddr <= ip2int("3.1.0.0") <= broadcast False
Or if the network is specified as an address and a mask, then to find out whether the specified network address belongs, you can use bitwise operations: (ip & netmask) == netaddr
:
>>> netaddr = ip2int('2.0.0.0') >>> bits = 12 # /12 >>> netmask = (~0 << (32 - bits)) & 0xffffffff >>> (ip2int("2.1.0.0") & netmask) == netaddr True >>> (ip2int("3.1.0.0") & netmask) == netaddr False
|