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
直接:
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)))
我没有要测试的 big-endian 机器,所以我不确定字节序是否取决于您的处理器架构,但如果是,请替换 <
struct.pack('<L', ...
with =
所以代码将使用机器的本机字节序.
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屋!