---
# System prepended metadata

title: check_IP_range.sh

---

# check_IP_range.sh

```shell=
#!/bin/bash
PROGNAME=$0
CIDR_REGEX_PATTERN="^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)(\/([1-9]|[1-2][0-9]|3[0-2])){0,1}$"

usage() {
  cat << EOF >&2
Usage: $PROGNAME [-c <CIDR>] [-f <file>]

-f <file>: ...
-c <CIDR>: ...
EOF
  exit 1
}

v4dec() {
  for i; do
    echo $i | {
      IFS=./
      read a b c d e
      test -z "$e" && e=32
      echo -n "$((a<<24|b<<16|c<<8|d)) $((-1<<(32-e))) "
      }
  done
}


get_ip_list_is_in_cidr() {
  while IFS= read -r ip; do
    v4dec $ip $CIDR | {
      read addr1 mask1 addr2 mask2
      if (( (addr1&mask2) == (addr2&mask2) && mask1 >= mask2 )); then
        echo "$ip"
      fi
    }
  done < "$IP_LIST_FILE"
}


while getopts 'c:f:' opts; do
  case $opts in
    f) IP_LIST_FILE=$OPTARG;;
    c) CIDR=$OPTARG;;
  esac
done

if ((OPTIND == 1))
then
    usage
    exit 1
fi

if [ -z "$IP_LIST_FILE" ] || [ -z "$CIDR" ]
then
   echo "missing parameters";
   usage
   exit 1
fi

if ! [[ $CIDR =~ $CIDR_REGEX_PATTERN ]]
then
    echo "CIDR $CIDR with wrong format"
    exit 1
fi

if [ ! -f "$IP_LIST_FILE" ]
then
   echo "IP list file $IP_LIST_FILE not exist"
   exit 1
fi

get_ip_list_is_in_cidr $CIDR $IP_LIST_FILE
```