简体   繁体   中英

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'. 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.

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. I just made this in a CentOS environment. If you are using Windows, just tweek the "ifconfig adapter-name" string... probably use "ipconfig /all" or something.

#! /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. Just replace that with your wifi card or ethernet card name as a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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