python netifaces - How to get currently used netwo

2019-05-19 02:24发布

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条回答
冷血范
2楼-- · 2019-05-19 02:47

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.

查看更多
登录 后发表回答