Skip to content

Instantly share code, notes, and snippets.

@tamirko
Last active April 3, 2024 17:08
Show Gist options
  • Save tamirko/78c8f8613f73df0625f0acc6b7a75d94 to your computer and use it in GitHub Desktop.
Save tamirko/78c8f8613f73df0625f0acc6b7a75d94 to your computer and use it in GitHub Desktop.
Check if ip address is in range in Python
# Prior to using this code, you need to run : pip install netaddr
from netaddr import *
from netaddr import iter_iprange
def is_in_subnet(input_addr, subnet_addr, subnet_mask):
current_subnet_str = '{0}/{1}'.format(subnet_addr, subnet_mask)
curr_subnet = IPNetwork(current_subnet_str)
for curr_ip in curr_subnet:
if input_addr == str(curr_ip):
print "{0} is in {1}".format(input_addr, current_subnet_str)
return
print "{0} is NOT in {1}".format(input_addr, current_subnet_str)
def is_in_range(curr_addr, start_range, end_range):
curr_ips_list = iter_iprange(start_range, end_range, step=1)
print "Scanning from {0} till {1}".format(first_ip, last_ip)
for curr_ip in curr_ips_list:
if str(curr_ip) == curr_addr:
print "The ip address {0} is in {1}-{2}".format(curr_ip, first_ip, last_ip)
return True
print "ip address {0} is NOT in {1}-{2}".format(curr_addr, first_ip, last_ip)
return False
subnet_address= "10.142.78.0"
subnet_mask= "255.255.255.248"
test_ip1 = "10.142.78.6"
is_in_subnet(test_ip1, subnet_address, subnet_mask)
first_ip = "192.168.1.1"
last_ip = "192.168.1.13"
test_ip2 = "192.168.1.8"
is_in_range(test_ip2, first_ip, last_ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment