Score:1

Check if IP Belongs to a CIDR

ro flag

We have a list of CIDR's

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

I want to check if a IP for example : 23.90.68.56 belongs to any of the above CIDR's. If yes then we get the output of that CIDR.

According the above example the output should be 23.90.68.0/24

I tried using grepcidr but I do not know how can we output that specific CIDR's

I am creating a bash script for this but can someone help me with this output thing? I tried searching the web but couldn't get anything relevant

Ron Maupin avatar
us flag
[This two-part answer](https://networkengineering.stackexchange.com/a/53994/8499) has a section that detail exactly how to see if an address belongs to a network (is in the same network as the network address). You mask both the network and target addresses with the network mask, and if the results are equal, then they are the same network.
jm flag
You can do this using `nmap`. Long-winded command line is `for net in 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; do nmap -sL -n $net | grep -q 23.90.68.56 && echo $net; done`. Easily changed to a script with parameters.
ph3ro avatar
ro flag
@doneal24 What if the list of cidrs are in a file??
Score:0
fr flag

You probably have Python:

#!/usr/bin/env python3
import argparse
import ipaddress
import sys

parser = argparse.ArgumentParser()
parser.add_argument("address")
args = parser.parse_args()

addr = ipaddress.ip_address(args.address)

for line in sys.stdin:
    cidr = ipaddress.ip_network(line.strip())
    if addr in cidr:
        print(cidr)
        exit(0)

exit(1)
Score:0
ar flag

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
Score:0
jm flag

A possible shell script:

#!/bin/bash

ip=$1
shift; shift

for net in "$@"
do
    nmap -sL -n $net | grep -q $ip && echo $net
done

If you need the list of cidrs in a file use ./scriptname ip_to_be_checked $(cat filename). Possibly a useless use of cat.

./cidr.sh 23.90.68.56 $(cat cidrs.txt)
jm flag
@ph3ro If this works for you, please consider accepting the answer. It makes it more searchable plus increases my reputation :).
user1686 avatar
fr flag
The second `shift` is excessive – it'll throw away $2 i.e. the first CIDR from the file.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.