Linux – How to determine eth0 gateway address when it is not the default gateway

iplinuxnetstatnetworking

In my system I have eth0 (which may or may not be connected) and a modem on ppp0 (which always may be up or down). The the case where both interfaces are up and ppp0 is the default route, I'd like to find a way to determine the gateway IP actual address of eth0. I tried "netstat -rn" but in this configuration the output is:

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
xx.xx.xxx.xxx   0.0.0.0         255.255.255.255 UH        0 0          0 ppp0
192.168.98.0    0.0.0.0         255.255.255.0   U         0 0          0 eth0
127.0.0.0       0.0.0.0         255.0.0.0       U         0 0          0 lo
0.0.0.0         0.0.0.0         0.0.0.0         U         0 0          0 ppp0

So how do I determine eth0's gateway address? In the above case the actual gateway address is 192.168.98.1.

Best Answer

Assume eth0 is DHCP client interface.
One option is to check the DHCP client lease files dhcpd.leases
Place and name depends on the system; on some Fedora systems, the files under /var/lib/dhclient/ are lease files, where the interesting string is like that :

  option routers 192.168.1.1;

Another option, which worked for me on a funtoo box: dhcpcd -U eth0
prints a nice table, ready to source in scripts

broadcast_address=192.168.1.255
dhcp_lease_time=86400
dhcp_message_type=5
dhcp_server_identifier=192.168.1.1
domain_name_servers='192.168.1.1 192.168.1.101'
ip_address=192.168.1.101
network_number=192.168.1.0
routers=192.168.1.1
subnet_cidr=24
subnet_mask=255.255.255.0

There other options like dhcping, dhclient -n, according to google and manpages, but they fail on my boxes, but may work for you.

Related Question