Last active
August 20, 2020 23:04
-
-
Save rawiriblundell/d34b02c4c1e685d28eef6eeb9e92e324 to your computer and use it in GitHub Desktop.
A function to validate whether an input is a valid ipv4 address
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
ipv4::validate_addr() { | |
# Disable SC2086 for 'set -- ${*%/*}' as we require this to be word split | |
# shellcheck disable=SC2086 | |
( | |
IFS=.; set -f; set -- ${*//\"/}; set -- ${*%/*} | |
local octet; local count=0; local errcount=0 | |
if (( "${#}" == 4 )); then | |
for octet in "${@}"; do | |
(( ++count )) | |
case "${octet}" in | |
(""|*[!0-9]*) | |
printf -- '%s\n' "Octet ${count} appears to be empty or non-numeric" >&2 | |
(( ++errcount )) | |
;; | |
(*) | |
if (( octet > 255 )); then | |
printf -- '%s\n' "Octet ${count} appears to be invalid (>255)" >&2 | |
(( ++errcount )) | |
fi | |
;; | |
esac | |
done | |
(( errcount > 0 )) && return 1 | |
else | |
printf -- '%s\n' "Input does not appear to be a valid IPv4 address" >&2 | |
return 1 | |
fi | |
# If we get to this point, then all should be ok | |
return 0 | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment