简体   繁体   English

不使用外部程序包即可获取所有NIC的IP地址

[英]Get IP address of all NIC's without using external package

I want to list ip address of all NICs connected to my machine (without using any external packages) 我想列出连接到我的计算机的所有NIC的IP地址(不使用任何外部软件包)

import socket
print socket.gethostbyname_ex(socket.gethostname())[2]

This code is working fine for Windows but on my Linux machine it outputs 127.0.1.1 这段代码在Windows上运行正常,但是在我的Linux机器上,它输出127.0.1.1

How do I change above code to make it work on Linux ? 如何更改以上代码以使其在Linux上运行?


The content of /etc/hostname is / etc / hostname的内容是

machine-name

And the content of /etc/hosts is / 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

I think your issue is the content of /etc/hosts , which is what socket is using to match the hostname to the IP addresses. 我认为您的问题是/ etc / hosts的内容,这是socket用来将主机名与IP地址匹配的内容。

If you change your /etc/hosts to the following, you should see both 127.0.0.1 and 127.0.1.1 on the list: 如果将/ etc / hosts更改为以下内容,则列表上应该同时看到127.0.0.1127.0.1.1

127.0.0.1 localhost machine-name
127.0.1.1 machine-name

# And of course your IPv6 settings below...

Any IP addresses which aren't in that file won't appear in the results of socket.gethostbyname_ex() . 该文件中没有的任何IP地址都不会出现在socket.gethostbyname_ex()的结果中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM