How to remove/exclude unwanted objects from a list in python

147 views Asked by At

Hi I am trying to get the IP of every interface on my machine using netifaces in python. I am still new to python and working my way through some concepts but it seems like I can query every NIC at once and then put the results into a list the problem is my end goal is to ask the user which network to work on and I want to exclude everything that returns 'No IP addr'.

I have already tried a few different methods including removing strings from the list and that didnt work or only adding IP addresses objects but im pretty sure im not doing it properly since it still errors out. Any help is appreciated.

import os
import socket
from netifaces import interfaces, ifaddresses, AF_INET

def get_self_IP():
    for ifaceName in interfaces():
        addresses = []
        possibilities = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
        print(' '.join(possibilities))
        for i in possibilities:
            if isinstance(i, ifaddress.ipaddress): # if i is an IP address
                addresses.append(i)
        print(addresses)

Also I have two lists now because ive changed it a few times to troubleshoot but if I can keep it as one list and only .append the IPs to it while its gathering IPs rather than have to do an entire separate list with a separate for or if loop it would be ideal but I do not know another way unfortunately.

1

There are 1 answers

2
d3lux1999 On BEST ANSWER

Not sure if this is what you want, but:

I changed the function to:

def get_self_IP():
  addresses = []
  for ifaceName in interfaces():
      ifaddresses_list = ifaddresses(ifaceName)
      possibilities = [i['addr'] for i in ifaddresses_list.setdefault(AF_INET, [{'addr': 'No IP addr'}])]
      for i in possibilities:
          if ifaddresses_list[2][0]['addr'] != "No IP addr":
              addresses.append(i)
  print(addresses)

The ifaddresses(ifaceName) returns a dictionary which apparently the key 2 contains the IP address in the index 0 with the key 'addr', which in case the IP doesn't exist the value is No IP addr. In that the if checks if that is not the case and then adds the IP address to the addresses list.

If I didn't understand what you want clearly, please answer with more details :)