为什么在 python 中无法使用 configparser 获取本地 IP

why can not get the local IP with configparser in 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

有人知道这是怎么回事吗?谢谢。

引用作为配置选项的一部分。

您的配置文件应如下所示;

[config]
ethname = eth0

注意省略引号。