Python: get default gateway for a local interface/ip address in linux

后端 未结 8 1663
礼貌的吻别
礼貌的吻别 2020-12-06 01:09

On Linux, how can I find the default gateway for a local ip address/interface using python?

I saw the question \"How to get internal IP, external IP and default gate

8条回答
  •  -上瘾入骨i
    2020-12-06 01:41

    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("

    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(' with = so the code will use the machine's native endianness.

提交回复
热议问题