Skip to content

Instantly share code, notes, and snippets.

@bebosudo
Created May 22, 2020 13:58
Show Gist options
  • Save bebosudo/d8ce58af796087e4dfa1d561919adfe7 to your computer and use it in GitHub Desktop.
Save bebosudo/d8ce58af796087e4dfa1d561919adfe7 to your computer and use it in GitHub Desktop.
Test if address is in network (in CIDR notation); IPv4 only, but IPv6 support should be easy
import socket, struct
def ip_addr_to_bin_str(ip):
# To support IPv6, play with socket.inet_pton.
return format(struct.unpack('!I', socket.inet_aton(ip))[0], 'b')
def ip_in_cidr_net(ip_address, cidr_network):
ip_bin = ip_addr_to_bin_str(ip_address)
# Extract the "base" IP from the network address
cidr_addr, cidr_size = cidr_network.split("/")
netmask_bin = ip_addr_to_bin_str(cidr_addr)[:int(cidr_size)]
return ip_bin.startswith(netmask_bin)
# ip_in_cidr_net('10.1.2.3', '10.0.0.0/8') -> True
# ip_in_cidr_net('10.0.0.8', '10.0.0.0/24') -> True
# ip_in_cidr_net('10.0.0.8', '10.0.0.78/24') -> True
# ip_in_cidr_net('10.0.0.8', '10.8.8.345/24') -> raises socket.error, useful if you want to test IPs found in movies
# ip_in_cidr_net('192.168.100.1', '192.168.100.0/22') -> True
# ip_in_cidr_net('192.168.103.255', '192.168.100.0/22') -> True
# ip_in_cidr_net('192.168.104.0', '192.168.100.0/22') -> False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment