On Linux, how can I find the default gateway for a local ip address/interface using python?
I saw the question “How to get internal IP, external IP and default gateway for UPnP”, but the accepted solution only shows how to get the local IP address for a network interface on windows.
Thanks.
Advertisement
Answer
For those people who don’t want an extra dependency and don’t like calling subprocesses, here’s how you do it yourself by reading /proc/net/route
directly:
JavaScript
x
13
13
1
import socket, struct
2
3
def get_default_gateway_linux():
4
"""Read the default gateway directly from /proc."""
5
with open("/proc/net/route") as fh:
6
for line in fh:
7
fields = line.strip().split()
8
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
9
# If not default route or not RTF_GATEWAY, skip it
10
continue
11
12
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
13
I don’t have a big-endian machine to test on, so I’m not sure whether the endianness is dependent on your processor architecture, but if it is, replace the <
in struct.pack('<L', ...
with =
so the code will use the machine’s native endianness.