Python:在Linux中获取本地接口/IP地址的默认网关
在Linux系统上,我怎么用Python找到一个本地IP地址或网络接口的默认网关呢?
我看到过一个问题是“如何获取内部IP、外部IP和UPnP的默认网关”,但是那个被接受的解决方案只展示了如何在Windows上获取网络接口的本地IP地址。
谢谢。
9 个回答
6
看起来http://pypi.python.org/pypi/pynetinfo/0.1.9这个东西可以做到这一点,不过我还没有试过。
20
为了完整性(也为了更详细地解释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/
37
对于那些不想增加额外依赖,也不喜欢调用子进程的人,这里有个方法可以直接通过读取 /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:
# If not default route or not RTF_GATEWAY, skip it
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
我没有大端机器来测试,所以不确定字节序是否依赖于你的处理器架构。如果是的话,可以把 <
替换成 =
,这样代码就会使用你机器本身的字节序。