3

So I have a centos or ubuntu docker container and discovered that there are no ip, netstat to ifconfig. I would not like to install any additional packages. Is there any way to get default gateway if none of mentioned commands are available?

PS I need default gateway in order to know how can I access docker host from container.

Kirill
  • 985
  • 3
  • 10
  • 20
  • Just discovered that I can get container ip with `hostname -i'. I can easily guess the default gateway until I have more than 254 containers running. – Kirill Sep 19 '17 at 21:36
  • 1
    See below stackexchange link for detailed answer [Where is routing table stored internally in the Linux kernel?](https://unix.stackexchange.com/questions/204260/where-is-routing-table-stored-internally-in-the-linux-kernel) – sibzz Sep 20 '17 at 06:34

4 Answers4

1

cat /proc/net/route gives you the complete routing table including default gateway, just like ip route. IP addresses are in hex and byte reversed, though.

dirkt
  • 31,679
  • 3
  • 40
  • 73
1

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
Nik V
  • 11
  • 1
0

In CentOS, you can get the Default Gateway details from /etc/sysconfig/network file

0

You can use the route command:

$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 eth1
192.168.1.0     0.0.0.0         255.255.255.0   U     1      0        0 eth1
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • It's fairly likely that `route` will also be unavailable when there's no `ifconfig` or `ip`. – TooTea Mar 19 '20 at 09:11