Created
August 16, 2021 11:47
-
-
Save SomajitDey/8fe8b750c739ccdd60a3acc5a218bb11 to your computer and use it in GitHub Desktop.
Check if any IPv4 address is private or public.
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 | |
# Brief: Given any IPv4 address check if it is private or public. IPv4 itself is not validated | |
# Exit code: 0 (private); 1 (public); 2 (neither private nor public) | |
# Usage: ipcheck <ip_addr> | |
_test(){ | |
# Brief: Test if given value if within given limits. No output. Just exitcode. | |
local limit1="${1}" value="${2}" limit2="${3}" | |
[[ "$(echo -e "${limit1}\n${value}\n${limit2}" | sort -V | awk NR==2)" == "${value}" ]] | |
# TODO: May be `-V` is not needed in `sort` | |
}; export -f _test | |
ip_addr="${1}" | |
[[ "${ip_addr}" == 127.0.0.1 ]] && exit 0 | |
_test 10.0.0.0 "${ip_addr}" 10.255.255.255 && exit 0 | |
_test 172.16.0.0 "${ip_addr}" 172.31.255.255 && exit 0 | |
_test 192.168.0.0 "${ip_addr}" 192.168.255.255 && exit 0 | |
[[ "${ip_addr}" == 0.0.0.0 ]] && exit 2 | |
_test 224.0.0.0 "${ip_addr}" 239.255.255.255 && exit 2 # Multicast addresses | |
exit 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment