Skip to content

Instantly share code, notes, and snippets.

@rawiriblundell
Last active August 20, 2020 23:04
Show Gist options
  • Save rawiriblundell/d34b02c4c1e685d28eef6eeb9e92e324 to your computer and use it in GitHub Desktop.
Save rawiriblundell/d34b02c4c1e685d28eef6eeb9e92e324 to your computer and use it in GitHub Desktop.
A function to validate whether an input is a valid ipv4 address
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