python netifaces - How to get currently used network interface

8.4k Views Asked by At

i using netifaces in python to get local ip address, but how to pick currently used (by system) network interface? Help me please. Thank you!

1

There are 1 best solutions below

1
On BEST ANSWER

It's still not entirely clear what you're asking, because a system does not necessarily have a singled "used" interface. A system may have multiple interfaces with addresses, and may be using all of them to contact different systems.

A system will usually (but not always!) have a "default route" out one interface, which is typically used to contact hosts to which the system is not directly connected. If this is what you want, you can use the Python netifaces module, like this:

>>> import netifaces
>>> def_gw_device = netifaces.gateways()['default'][netifaces.AF_INET][1]

This will get you the name of the device used by the default IPv4 route. You can get the MAC address of that interface like this:

>>> macaddr = netifaces.ifaddresses('enp0s25')[netifaces.AF_LINK][0]['addr']

You can of course get the same information by parsing the output of the ip command, but using the netifaces module is much cleaner.