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.
This commit is contained in:
D. Berge
2025-08-09 22:23:50 +02:00
parent db97382758
commit b8b25dcd62
2 changed files with 39 additions and 16 deletions

View File

@@ -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"