当我想使用python脚本获取IP地址时,如何更正IOError:[Errno 6]?

2024-06-16 08:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用这个python脚本获取OSX IP addr时,总是点击IOError:[Errno 6]Device not configured,并没有得到问题的症结所在。在

 import socket
    import fcntl
    import struct
    def get_ip_address(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15])
        )[20:24])
    get_ip_address('lo')
    # '127.0.0.1'
    get_ip_address('eth0')
    # '38.113.228.130'
    get_ip_address('ppp0')
    # '123.163.166.00'

谢谢你的帮助。 弗兰克


Tags: importip脚本getaddressdevicesocketstruct