/etc/hostname的内容为
我想列出连接到我的机器的所有网卡的ip地址(不使用任何外部包)
import socket
print socket.gethostbyname_ex(socket.gethostname())[2]
这段代码在Windows上运行良好,但在我的Linux机器上它输出127.0.1.1
我如何改变上面的代码使其在Linux上工作?
/etc/hostname的内容为
machine-name
/etc/hosts内容为
127.0.0.1 localhost
127.0.1.1 machine-name
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
我认为你的问题是/etc/hosts的内容,这是socket
用来匹配主机名和IP地址的。
如果您将/etc/hosts更改为以下内容,您应该在列表中看到127.0.0.1
和127.0.1.1
:
127.0.0.1 localhost machine-name
127.0.1.1 machine-name
# And of course your IPv6 settings below...
任何不在该文件中的IP地址都不会出现在socket.gethostbyname_ex()
的结果中