Python: get default gateway for a local interface/ip address in linux Python: get default gateway for a local interface/ip address in linux python python

Python: get default gateway for a local interface/ip address in linux


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:

import socket, structdef get_default_gateway_linux():    """Read the default gateway directly from /proc."""    with open("/proc/net/route") as fh:        for line in fh:            fields = line.strip().split()            if fields[1] != '00000000' or not int(fields[3], 16) & 2:                # If not default route or not RTF_GATEWAY, skip it                continue            return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))

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.


For completeness (and to expand on alastair's answer), here is an example that uses "netifaces" (tested under Ubuntu 10.04, but this should be portable):

$ sudo easy_install netifacesPython 2.6.5 (r265:79063, Oct  1 2012, 22:04:36)...$ ipython...In [8]: import netifacesIn [9]: gws=netifaces.gateways()In [10]: gwsOut[10]:{2: [('192.168.0.254', 'eth0', True)], 'default': {2: ('192.168.0.254', 'eth0')}}In [11]: gws['default'][netifaces.AF_INET][0]Out[11]: '192.168.0.254'

Documentation for 'netifaces': https://pypi.python.org/pypi/netifaces/