Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Last active July 21, 2022 05:19
Show Gist options
  • Save smartwatermelon/5d5ad37c40171f31796ef544c1955cba to your computer and use it in GitHub Desktop.
Save smartwatermelon/5d5ad37c40171f31796ef544c1955cba to your computer and use it in GitHub Desktop.
@cassidoo's interview question from July 11, 2021
#!/usr/bin/env bash
set -eu -o pipefail
# Given an IPv4 address and a netmask in CIDR notation, return a boolean
# specifying whether the IP address is inside the given range.
# requirements:
# # bash version >= 4
# # 'grepcidr' command (http://www.pc-tools.net/unix/grepcidr/)
if [ "${BASH_VERSINFO:-0}" -lt 4 ]; then
echo "$(basename $0): Bash version 4 or greater is required. Found BASH_VERSION: ${BASH_VERSION}"
exit 1
fi
declare -A DEPS=( ["grepcidr"]="grepcidr" )
ERR=""
for DEP in "${!DEPS[@]}"; do
if ! command -v "${DEP}" >/dev/null; then
ERR="${ERR}\nDependency not satisfied: ${DEP}; please install this to continue. On macOS you can do 'brew install ${DEPS[$DEP]}'"
fi
done
if [ ! -z "${ERR}" ]; then
echo -e "${ERR}"
exit 1
fi
if [ $# -ne 2 ]; then
echo -e "$(basename $0): enter an IPv4 address and a netmask in CIDR notation, e.g\n\t192.168.4.27 192.168.0.0/16"
exit 1
fi
IPV4=$1
CIDR=$2
TMPFILE="$(mktemp)"
echo "${IPV4}" > $TMPFILE
if grepcidr "${CIDR}" "${TMPFILE}" >/dev/null; then
echo "true"
else
echo "false"
fi
@smartwatermelon
Copy link
Author

MONTASIO:~ andrewrich$ ~/Documents/scripts/inRange.sh 192.168.4.27 192.168.0.0/16
true
MONTASIO:~ andrewrich$ ~/Documents/scripts/inRange.sh 192.168.4.27 192.168.1.0/24
false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment