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

后端 未结 8 1575
礼貌的吻别
礼貌的吻别 2020-12-06 01:09

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 gate

相关标签:
8条回答
  • 2020-12-06 01:35

    It seems http://pypi.python.org/pypi/pynetinfo/0.1.9 can do this, but I haven't tested it.

    0 讨论(0)
  • 2020-12-06 01:38

    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 netifaces
    Python 2.6.5 (r265:79063, Oct  1 2012, 22:04:36)
    ...
    $ ipython
    ...
    In [8]: import netifaces
    In [9]: gws=netifaces.gateways()
    In [10]: gws
    Out[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/

    0 讨论(0)
  • 2020-12-06 01:41

    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, struct
    
    def 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.

    0 讨论(0)
  • 2020-12-06 01:42

    You can get it like this (Tested with python 2.7 and Mac OS X Capitain but should work on GNU/Linux too): import subprocess

    def system_call(command):
        p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
        return p.stdout.read()
    
    
    def get_gateway_address():
        return system_call("route -n get default | grep 'gateway' | awk '{print $2}'")
    
    print get_gateway_address()
    
    0 讨论(0)
  • 2020-12-06 01:46

    The latest version of netifaces can do this too, but unlike pynetinfo, it will work on systems other than Linux (including Windows, OS X, FreeBSD and Solaris).

    0 讨论(0)
  • 2020-12-06 01:46

    for Mac:

    import subprocess
    
    def get_default_gateway():
        route_default_result = str(subprocess.check_output(["route", "get", "default"]))
        start = 'gateway: '
        end = '\\n'
        if 'gateway' in route_default_result:
            return (route_default_result.split(start))[1].split(end)[0]
    
    print(get_default_gateway())
    
    0 讨论(0)
提交回复
热议问题