in python, that would be:
import socket
def is_ip_in_cidr(ip, cidr):
network, mask = cidr.split("/")
mask = int(mask)
ip_int = int.from_bytes(socket.inet_aton(ip), "big")
network_int = int.from_bytes(socket.inet_aton(network), "big")
network_mask = (0xFFFFFFFF << (32 - mask)) & 0xFFFFFFFF
return (ip_int & network_mask) == network_int
# Test the function with a sample IP address and CIDR
ip = "192.168.0.5"
cidr = "192.168.0.0/24"
if is_ip_in_cidr(ip, cidr):
print(f"{ip} is in {cidr}")
else:
print(f"{ip} is NOT in {cidr}")
if you can use the list provided as a fixed set to test like so:
import socket
def is_ip_in_cidr(ip, cidrs):
for cidr in cidrs:
network, mask = cidr.split("/")
mask = int(mask)
ip_int = int.from_bytes(socket.inet_aton(ip), "big")
network_int = int.from_bytes(socket.inet_aton(network), "big")
network_mask = (0xFFFFFFFF << (32 - mask)) & 0xFFFFFFFF
if (ip_int & network_mask) == network_int:
return True
return False
# Test the function with a sample IP address and list of CIDRs
ip = "192.168.0.5"
cidrs = ["1.10.10.0/24", "5.154.0.0/16", "5.181.219.0/24", "23.90.68.0/24", "31.40.214.0/24"]
if is_ip_in_cidr(ip, cidrs):
print(f"{ip} is in one of {cidrs}")
else:
print(f"{ip} is NOT in any of {cidrs}")
in bash
#!/bin/bash
function is_ip_in_cidr {
local ip=$1
local cidr=$2
local network=$(echo $cidr | cut -d/ -f1)
local mask=$(echo $cidr | cut -d/ -f2)
local network_dec=$(echo $network | awk -F. '{printf("%d\n", ($1 * 256 + $2) * 256 + $3)}')
local ip_dec=$(echo $ip | awk -F. '{printf("%d\n", ($1 * 256 + $2) * 256 + $3)}')
local mask_dec=$((0xffffffff << (32 - $mask)))
if [[ $((ip_dec & mask_dec)) -eq $((network_dec & mask_dec)) ]]; then
echo "true"
else
echo "false"
fi
}
# Test the function with a sample IP address and CIDR
ip="192.168.0.5"
cidr="192.168.0.0/24"
if $(is_ip_in_cidr $ip $cidr); then
echo "$ip is in $cidr"
else
echo "$ip is NOT in $cidr"
fi