I want to detect the available network interfaces that is connected to a DHCP and got an IP from it. I am using following script to generate the list of available adapters.
import psutil
addrs = psutil.net_if_addrs()
all_network_interfaces = addrs.keys()
available_networks = []
for value in all_network_interfaces:
if addrs[value][1][1].startswith("169.254"):
continue
else:
available_networks.append(value)
print(available_networks)
The ones that starts with 169.254 are the adapters that is using Automatic Private IP Addressing (APIPA) so I want to filter them out. When I connect with an Ethernet cable, this script shows the related adapter, if I also connect over WiFi while ethernet is still connected, it adds the WiFi to the list. However, after disconnecting from the WiFi, WiFi adapters still holds the IP and still exists in the list. I think that it is a problem( maybe feature) with my adapter card. What is the best way to bypass this and obtain only the adapters with DHCP connection?
With psutil.net_if_stats() to get only up and running network interfaces:
import psutil
addresses = psutil.net_if_addrs()
stats = psutil.net_if_stats()
available_networks = []
for intface, addr_list in addresses.items():
if any(getattr(addr, 'address').startswith("169.254") for addr in addr_list):
continue
elif intface in stats and getattr(stats[intface], "isup"):
available_networks.append(intface)
print(available_networks)
Sample output:
['lo0', 'en0', 'en1', 'en2', 'en3', 'bridge0', 'utun0']
There is a python package get-nic which gives NIC status, up\down, ip addr, mac addr etc
pip install get-nic
from get_nic import getnic
getnic.interfaces()
Output: ["eth0", "wlo1"]
interfaces = getnic.interfaces()
getnic.ipaddr(interfaces)
Output:
{'lo': {'state': 'UNKNOWN', 'inet4': '127.0.0.1/8', 'inet6': '::1/128'}, 'enp3s0': {'state': 'DOWN', 'HWaddr': 'a4:5d:36:c2:34:3e'}, 'wlo1': {'state': 'UP', 'HWaddr': '48:d2:24:7f:63:10', 'inet4': '10.16.1.34/24', 'inet6': 'fe80::ab4a:95f7:26bd:82dd/64'}}
Refer GitHub page for more information: https://github.com/tech-novic/get-nic-details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With