在python中确定CONNECTED接口(linux)的IP地址

时间:2010-10-07 19:24:55

标签: python linux networking ip-address

在我的linux机器上,3个网络接口中的1个实际上可能连接到互联网。我需要获取当前连接接口的IP地址,请记住我的其他2个接口可能被分配了IP地址,但没有连接。

我可以通过我的每个接口ping一个网站,以确定哪个接口有连接,但我想比等待ping超时更快。而且我不想依赖外部网站。

更新

我的所有接口都可能有ip地址和网关。这适用于嵌入式设备。因此,我们允许用户在eth0eth1之间进行选择。但是如果界面上没有用户告诉我们使用的连接,我们会回过头来说eth2(理论上)它将始终有效。

所以我需要做的是首先检查用户的选择是否已连接,如果是,则返回该IP。否则我需要获得eth2的IP。我可以很好地获得接口的IP,它只是确定哪一个实际连接。

2 个答案:

答案 0 :(得分:0)

如果系统的默认网关是可靠的,那么从route -n的输出中获取包含" UG "的行(注意空格)也将包含网关的IP和接口名称活动界面。

答案 1 :(得分:0)

解决方案在这里:http://code.activestate.com/recipes/439093-get-names-of-all-up-network-interfaces-linux-only/


import fcntl
import array
import struct
import socket
import platform
"""
global constants.  If you don't like 'em here,
move 'em inside the function definition.
"""
SIOCGIFCONF = 0x8912
MAXBYTES = 8096

def localifs():
    """
    Used to get a list of the up interfaces and associated IP addresses
    on this machine (linux only).

    Returns:
    List of interface tuples.  Each tuple consists of
    (interface name, interface IP)
    """
    global SIOCGIFCONF
    global MAXBYTES

    arch = platform.architecture()[0]

    # I really don't know what to call these right now
    var1 = -1
    var2 = -1
    if arch == '32bit':
        var1 = 32
        var2 = 32
    elif arch == '64bit':
        var1 = 16
        var2 = 40
    else:
        raise OSError("Unknown architecture: %s" % arch)

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', '\0' * MAXBYTES)
    outbytes = struct.unpack('iL', fcntl.ioctl(
        sock.fileno(),
        SIOCGIFCONF,
        struct.pack('iL', MAXBYTES, names.buffer_info()[0])
        ))[0]

    namestr = names.tostring()
    return [(namestr[i:i+var1].split('\0', 1)[0], socket.inet_ntoa(namestr[i+20:i+24])) \
            for i in xrange(0, outbytes, var2)]


print localifs()