pythonnetwork-protocols

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.


Solution

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