From 47c971a0fcface1dd2ffefcc946b215297d390c7 Mon Sep 17 00:00:00 2001 From: Gitouche <26656-gitouche@users.noreply.framagit.org> Date: Thu, 23 Sep 2021 22:32:22 +0200 Subject: [PATCH] add function to get default route ipv4 --- functions.sh | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/functions.sh b/functions.sh index 5482d76..51ea99d 100644 --- a/functions.sh +++ b/functions.sh @@ -78,6 +78,37 @@ ensure_variables_are_defined () { done } +# check if IPv4 syntax is valid +check_valid_ipv4() { + re='^((1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}' + re+='(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))$' + + if [[ ${1} =~ ${re} ]]; then + return 0 + else + echo "ERROR : ${1} is not a valid IPv4 address" + exit 1 + fi +} + +# Get default interface IPv4 address +# and return result in variable passed as argument +get_default_iface_ipv4() { + # Call this function with the name of the variable + # you want to store the result in : + # default_iface_ipv4 myipv4 + # See https://www.linuxjournal.com/content/return-values-bash-functions + local __resultvar=${1} + local __default_iface=$(awk '$2 == 00000000 { print $1 }' /proc/net/route) + local __default_iface_ipv4=$(ip addr show dev "${__default_iface}" | awk '$1 == "inet" { sub("/.*", "", $2); print $2 }') + if check_valid_ipv4 ${__default_iface_ipv4}; then + eval $__resultvar="'${__default_iface_ipv4}'" + return 0 + else + exit 1 + fi +} + # ok if systemd unit file {1} exists ensure_systemd_unit_exists () { if ! check_systemd_unit_exists ${1}; then