[英]Python netifaces gives two address
I am trying to get the ip address and broadcast address of my machine and after a lot of research netifaces works fine but the problem is ip address prints properly but when i wanted the broadcast address it gives the docker broadcast address as well as the 'lo' broadcast address but i wanted only 'lo' broadcast address and i am not sure how to get only the broadcast address associated with 'lo'. 我正在尝试获取机器的ip地址和广播地址,经过大量研究netifaces可以正常工作,但是问题是ip地址可以正确打印,但是当我想要广播地址时,它会给出docker广播地址以及'lo广播地址,但我只想要“ lo”广播地址,我不确定如何仅获取与“ lo”相关联的广播地址。 Please help me with some ideas. 请帮我一些想法。 Also i am not sure that i have mentioned that wanted only 'lo' broadcast address but it also gives me dockers broadcast address as well. 另外我不确定我是否提到过只想要“ lo”广播地址,但是它也给了我dockers广播地址。
Code: 码:
import netifaces
interfaces=netifaces.interfaces()
for i in interfaces:
if i=='lo':
continue
iface= netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
bd=(j['broadcast'])
print(bd)
Output: 输出:
192.169.x.x('lo'-broadcast) 175.17.x.x ('docker'-broadcast)
Why are you trying to get lo? 你为什么要去弄? That is typically local loopback and will always have 127.0.0.1. 这通常是本地环回,并且始终具有127.0.0.1。 I just made this in a CentOS environment. 我只是在CentOS环境中做到的。 If you are using Windows, just tweek the "ifconfig adapter-name" string... probably use "ipconfig /all" or something. 如果您使用的是Windows,则只需在星期几输入“ ifconfig adapter-name”字符串...就可以使用“ ipconfig / all”之类的东西。
#! /usr/bin/python
import os
import re
def get_ip_data(ether_adapter):
ip_list = []
ip_data = os.popen("ifconfig " + ether_adapter)
for line in ip_data:
match1 = re.search(r'inet\s+(\d+.\d+.\d+.\d+)', line)
match2 = re.search(r'broadcast\s+(\d+.\d+.\d+.\d+)', line)
if match1:
ip = match1.group(1)
ip_list.append(ip)
if match2:
bcast = match2.group(1)
ip_list.append(bcast)
return ip_list
if __name__ == "__main__":
ethernet_card = "virbr0"
inet_list = get_ip_data(ethernet_card)
for element in inet_list:
print(element)
[root@server Desktop]# ./ip.py
192.168.122.1
192.168.122.255
In the client "virbr0" is the name of my wifi card. 在客户端中,“ virbr0”是我的wifi卡的名称。 Just replace that with your wifi card or ethernet card name as a string. 只需将其替换为您的wifi卡或以太网卡名称作为字符串即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.