Liondancer
Liondancer

Reputation: 16469

Script to find all network adapters I'm connected to in Python

I have a laptop that is connected to my organization's network using one or more network adapters. I'm not sure how to start this or where I should look for native python methods or other resources.

I was wondering how can I discover all the network adapters or NICs I am connected to using python. I want to try to accomplish this without a 3rd party library but if I have to that is fine as well.

I ultimately want to be able to write a tool that will continuously monitor the connectivity status and connection quality of each network. However I first have to find out which and how many network adapters I'm connected to.

Upvotes: 1

Views: 1703

Answers (2)

b-jazz
b-jazz

Reputation: 908

I needed something similar recently and came up with the following solution using psutil:

>>> import psutil

>>> psutil.net_if_addrs().keys()
dict_keys(['lo', 'eth0', 'docker0'])

I'm not claiming this is better, faster, more appropriate or more lightweight than the current accepted answer. I just thought it would be good to document other solutions to the problem.

Upvotes: 0

NPE
NPE

Reputation: 500713

netifaces would be a good start. From the docs:

It's been annoying me for some time that there's no easy way to get the address(es) of the machine's network interfaces from Python. [...]

This package attempts to solve that problem.

Some relevant examples:

>>> netifaces.interfaces()
['lo0', 'gif0', 'stf0', 'en0', 'en1', 'fw0']

>>> netifaces.ifaddresses('lo0')
{18: [{'addr': ''}],
  2: [{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}],
 30: [{'peer': '::1', 'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', 'addr': '::1'}, {'peer': '', 'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::1%lo0'}]}

Get it with pip install netifaces.

Upvotes: 1

Related Questions