Skip to content

Instantly share code, notes, and snippets.

@netmanchris
Last active August 29, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save netmanchris/26acb9880fffe5b4f36c to your computer and use it in GitHub Desktop.
Save netmanchris/26acb9880fffe5b4f36c to your computer and use it in GitHub Desktop.
Find netrange from two IP addresses
import ipaddress
def ip_in_network(startIp, endIp):
mask = 32
startIp = ipaddress.ip_address(startIp)
endIp = ipaddress.ip_address(endIp)
netrange = ipaddress.ip_network(str(startIp)+'/'+str(mask), strict=False)
while ((endIp in netrange) == False):
mask -= 1
netrange = ipaddress.ip_network(str(startIp)+'/'+str(mask), strict=False)
return netrange
@vcabbage
Copy link

Couple notes, it's generally considered more idiomatic to use string formatting rather than concatenation. This is usually easier to read and you don't need to explicitly convert to str. (It's also more efficient due to how strings are implemented.)

So str(startIp)+'/'+str(mask) could be written as '{}/{}'.format(startIp, mask).

Also, instead of while ((endIp in netrange) == False) you can write while endIp not in netrange.

Another option would be to write it as a for loop. I prefer this because it's shorter and reduces duplicate code, but it's really personally preference.

import ipaddress

def ip_in_network(startIp, endIp):
    startIp = ipaddress.ip_address(startIp)
    endIp = ipaddress.ip_address(endIp)
    for mask in range(32, -1, -1):
        netrange = ipaddress.ip_network('{}/{}'.format(startIp, mask), strict=False)
        if endIp in netrange:
            return netrange

(The range statement creates a list going from 32 to 0.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment