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
    I would pervy in the number of IP (just 32 bits) and then stupid to compare what is more. - pavel
  • 3
    docs.python.org/3/library/ipaddress.html Python has a standard library for this. (but only in 3.x) - andy.37

2 answers 2

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 
  • one
    I 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

In Python 3 :

 >>> 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 

In Python 2 :

 >>> 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