python-2.7comparisonip-addresssubnetnetmask

Compare if subnet is in IP range, in Python?


I have a set of subnets with labeled descriptions in a csv file. I need to assign these descriptions to the Data Probe ranges that these subnets belong to in another csv file.

Given a subnet with an ipaddress 34.0.0.0 and netmask 255.255.0.0,
I want to check if the subnet is in the range 34.163.83.230-34.163.83.230

I have considered creating a range from the subnet's ip and net mask and comparing it to the Data Probe ranges. I haven't been able to find out if this would yield the correct answer.

I cannot use the latest version of Python (this has to work with an application running python 2.7), so the ipaddress module is not an option for me.


Solution

  • The socket module provides inet_aton, which will convert your addresses to bitstrings. You can then convert them to integers using struct.unpack, mask using &, and use integer comparison:

    from socket import inet_aton
    from struct import unpack
    
    def atol(a):
        return unpack(">L", inet_aton(a))[0]
    
    addr = atol("30.44.230.0")
    mask = atol("255.255.0.0")
    lo = atol("32.44.230.0")
    hi = atol("32.44.230.255")
    prefix = addr & mask
    
    print lo <= prefix <= hi