Python:获取linux中本地接口/ IP地址的默认网关

GnP*_*GnP 12 python linux networking routing

在Linux上,如何使用python找到本地IP地址/接口的默认网关?

我看到了"如何获取UPnP的内部IP,外部IP和默认网关"的问题,但是接受的解决方案仅显示了如何在Windows上获取网络接口的本地IP地址.

谢谢.

sso*_*low 28

对于那些不想要额外依赖并且不喜欢调用子进程的人来说,这是你通过/proc/net/route直接阅读自己做的方式:

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:
                continue

            return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
Run Code Online (Sandbox Code Playgroud)

我没有要测试的big-endian机器,所以我不确定endianness是否依赖于你的处理器架构,但如果是,则替换<in struct.pack('<L', ...,=这样代码将使用机器的本机字节序.


the*_*ain 12

为了完整性(并扩展alastair的答案),这里有一个使用"netifaces"的例子(在Ubuntu 10.04下测试,但这应该是可移植的):

$ 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'
Run Code Online (Sandbox Code Playgroud)

"netifaces"的文档:https://pypi.python.org/pypi/netifaces/


小智 6

似乎http://pypi.python.org/pypi/pynetinfo/0.1.9可以做到这一点,但我还没有测试过.