Last active
August 29, 2015 14:28
-
-
Save netmanchris/26acb9880fffe5b4f36c to your computer and use it in GitHub Desktop.
Find netrange from two IP addresses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 writewhile 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.
(The range statement creates a list going from 32 to 0.)