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!
-
What do you mean by "currently used"? A system may have multiple active network interface (and each interfaces may have multiple ip addresses).larsks– larsks2015-06-07 21:37:51 +00:00Commented Jun 7, 2015 at 21:37
-
I mean preferred network interfaces. For example, i have eth0 and wlan0. eth0 is preferred interface and this is what i want to get.user3578984– user35789842015-06-08 12:57:13 +00:00Commented Jun 8, 2015 at 12:57
-
How is it "preferred"? Do you mean, "how do I figure out which interface is being used as the default route?"larsks– larsks2015-06-08 12:58:55 +00:00Commented Jun 8, 2015 at 12:58
-
Yes, somethink like that. Simply determine the current used interface in pythonuser3578984– user35789842015-06-08 13:39:35 +00:00Commented Jun 8, 2015 at 13:39
-
Example: mymac = "getHwAddr('determinate current used interface')"user3578984– user35789842015-06-08 13:41:57 +00:00Commented Jun 8, 2015 at 13:41
1 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.
1 Comment
netifaces documentation spells out these complications and common false assumptions in a fair amount of detail.