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

在Linux上,如何使用pythonfind本地ip地址/接口的默认网关?

我看到了“如何获得内部IP,外部IP和默认网关的UPnP”的问题,但接受的解决scheme只显示如何获得Windows上的networking接口的本地IP地址。

谢谢。

    对于那些不需要额外依赖并且不喜欢调用子进程的人,可以直接通过/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))) 

    我没有一个大端机器来测试,所以我不确定是否endianness是依赖于你的处理器架构,但如果是,替换< struct.pack('<L', ... with =所以代码将使用机器的本地排序。

    为了完整性(并扩展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' 

    “netifaces”的文档: https ://pypi.python.org/pypi/netifaces/

    netifaces的最新版本也可以这样做,但是与pynetinfo不同的pynetinfo ,它可以在Linux以外的系统(包括Windows,OS X,FreeBSD和Solaris)上运行。

     def get_ip(): file=os.popen("ifconfig | grep 'addr:'") data=file.read() file.close() bits=data.strip().split('\n') addresses=[] for bit in bits: if bit.strip().startswith("inet "): other_bits=bit.replace(':', ' ').strip().split(' ') for obit in other_bits: if (obit.count('.')==3): if not obit.startswith("127."): addresses.append(obit) break return addresses 

    你可以像这样得到它(用python 2.7和Mac OS X Capitain测试,但也可以在GNU / Linux上运行):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()