From b8b25dcd62252829c8faacfb049193eae161a06f Mon Sep 17 00:00:00 2001 From: "D. Berge" Date: Sat, 9 Aug 2025 22:23:50 +0200 Subject: [PATCH] Update IP getter script to return LAN address. get-ip.sh internet: returns the first IP address found that has internet access. get-ip.sh local (or no argument): returns the list of non-loopback IPs minus the one that has internet access. This means that update-dns.sh now sends the first IP address that does *not* have internet access. --- sbin/get-ip.sh | 53 +++++++++++++++++++++++++++++++++------------- sbin/update-dns.sh | 2 +- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/sbin/get-ip.sh b/sbin/get-ip.sh index 77c4510..34d4669 100755 --- a/sbin/get-ip.sh +++ b/sbin/get-ip.sh @@ -1,19 +1,42 @@ #!/bin/bash -# Find the interface used for the default route (e.g., to reach 8.8.8.8) -INTERFACE=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}') +# Function to get the internet IP +get_internet_ip() { + INTERFACE=$(ip route get 8.8.8.8 2>/dev/null | awk '{for(i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}') -if [ -z "$INTERFACE" ] || [ "$INTERFACE" = "lo" ]; then - echo "No valid default route found." >/dev/stderr - exit 1 + if [ -z "$INTERFACE" ] || [ "$INTERFACE" = "lo" ]; then + return 1 + fi + + IP=$(ip -4 addr show dev "$INTERFACE" scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)' | head -n1) + + if [ -z "$IP" ]; then + return 1 + fi + + echo "$IP" + return 0 +} + +# Get all global non-loopback IPv4 addresses +ALL_IPS=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)') + +ARG="${1:-local}" + +if [ "$ARG" = "internet" ]; then + INTERNET_IP=$(get_internet_ip) + if [ $? -ne 0 ]; then + echo "No valid default route or global IPv4 address found." + exit 1 + fi + echo "$INTERNET_IP" +else + # For "local" or anything else + INTERNET_IP=$(get_internet_ip) || INTERNET_IP="" # If fails, set to empty so no exclusion + + for IP in $ALL_IPS; do + if [ "$IP" != "$INTERNET_IP" ]; then + echo "$IP" + fi + done fi - -# Extract the primary IPv4 address from the interface (excluding loopback) -IP=$(ip -4 addr show dev "$INTERFACE" scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)' | head -n1) - -if [ -z "$IP" ]; then - echo "No global IPv4 address found on $INTERFACE." >/dev/stderr - exit 1 -fi - -echo "$IP" diff --git a/sbin/update-dns.sh b/sbin/update-dns.sh index 088bddf..9bce061 100755 --- a/sbin/update-dns.sh +++ b/sbin/update-dns.sh @@ -16,7 +16,7 @@ fi IP_SCRIPT="$HOME/software/sbin/get-ip.sh" # Get the current IPv4 address -IP_ADDRESS=$("$IP_SCRIPT") +IP_ADDRESS=$("$IP_SCRIPT" |head -n1) if [ -z "$IP_ADDRESS" ]; then echo "Error: Failed to retrieve IP address from $IP_SCRIPT"