Last active
July 21, 2022 05:19
-
-
Save smartwatermelon/5d5ad37c40171f31796ef544c1955cba to your computer and use it in GitHub Desktop.
@cassidoo's interview question from July 11, 2021
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Author
smartwatermelon
commented
Jul 12, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment