Skip to content Skip to sidebar Skip to footer

Detecting Available Network Adapters With Python

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

Solution 1:

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

Solution 2:

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


Post a Comment for "Detecting Available Network Adapters With Python"