Python:在Linux中获取本地接口/IP地址的默认网关 [英] Python: get default gateway for a local interface/ip address in linux
问题描述
在Linux上,如何使用python查找本地IP地址/接口的默认网关?
On Linux, how can I find the default gateway for a local ip address/interface using python?
我看到了一个问题:如何获取UPnP的内部IP,外部IP和默认网关",但是公认的解决方案仅显示了如何获取Windows网络接口的本地IP地址.
I saw the question "How to get internal IP, external IP and default gateway for UPnP", but the accepted solution only shows how to get the local IP address for a network interface on windows.
谢谢.
推荐答案
对于那些不希望额外依赖并且不喜欢调用子流程的人,这是您直接阅读/proc/net/route
的方法: /p>
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:
continue
return socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
我没有要测试的大字节序计算机,因此我不确定字节序是否取决于您的处理器体系结构,但是如果是,请将struct.pack('<L', ...
中的<
替换为
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.
这篇关于Python:在Linux中获取本地接口/IP地址的默认网关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!