As @dirkt mentioned, the default routing table is stored as text in /proc/net/route on any modern Linux system, but unfortunately the IP addresses are stored in (reversed) hex. With a little bash hacking and an assist from awk and sed we can turn this into a human readable ip address:
for i in $(echo "$(< /proc/net/route | head -2 | tail -1 | awk '{print $3}')" | sed -E 's/(..)(..)(..)(..)/\4 \3 \2 \1/' ) ; do printf "%d." $((16#$i)); done | sed 's/.$//'
Here's the same idea in a more readable (and multi-line) version:
#!/usr/bin/env bash
get-default-gateway() {
default_route_ip="$(< /proc/net/route | head -2 | tail -1 | awk '{print $3}')"
hex-ip-to-dec-ip "$default_route_ip"
}
hex-ip-to-dec-ip() {
local hex_ip="$1"
for i in $(echo "$hex_ip" | sed -E 's/(..)(..)(..)(..)/\4 \3 \2 \1/' ) ; do
printf "%d." $((16#$i));
done | sed 's/.$//'
}
get-default-gateway