本文介绍了Python:在 linux 中获取本地接口/IP 地址的默认网关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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)))

我没有要测试的大端机器,所以我不确定字节顺序是否取决于您的处理器架构,但如果是,请将 < 替换为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 地址的默认网关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:44