如何在python中使用configparser无法获取本地IP

2024-06-16 11:19:16 发布

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

我经营这条Python。一切都很好。你知道吗

import socket
import sys
def get_local_ip(ifname):
    print type(ifname)
    import fcntl, struct 
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15])) 
    ret = socket.inet_ntoa(inet[20:24]) 
    return ret 

输出

<type 'str'>
192.168.1.250

但我试图设置一个配置文件

这是我的配置文件 socketConfig.conf文件你知道吗

[config]
ethname = 'eth0'

下面是python代码

import socket
import sys
import configparser
conf = configparser.ConfigParser()
conf.read("socketConfig.conf")


def get_local_ip(ifname):
    print type(ifname)
    import fcntl, struct 
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15])) 
    ret = socket.inet_ntoa(inet[20:24]) 
    return ret

eth = conf.get('config', 'ethname').encode('utf-8')
print get_local_ip(eth)

然后把这些错误

<type 'str'>
Traceback (most recent call last):
  File "socketClient.py", line 28, in <module>
    print get_local_ip(eth)
  File "socketClient.py", line 23, in get_local_ip
    inet = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
IOError: [Errno 19] No such device

有人知道发生了什么吗?谢谢您。你知道吗


Tags: importipgetlocalconftypesocketstruct