How methods are chosen and used¶
get_mac_address() covers most uses of getmac. This page covers the internal methods used by getmac to resolve MAC addresses on various platforms.
Internally, getmac picks a method for each kind of lookup. The method is a class that knows a particular way of finding a MAC address, such as reading /sys/class/net/<iface>/address or running ip neighbor show. This page explains how those methods are chosen and used. To change them in your own code, see Customizing methods at runtime. To contribute a method to getmac, see Adding a new method.
Warning
Most of what this page describes lives in getmac.getmac and is an internal API that may change between releases. Use it with care.
Architecture describes where everything lives in the package. Every built-in method and its docstring is listed in the API.
Methods 101¶
Methods¶
A method is a subclass of Method and should set 3 attributes:
platforms: a set with the platforms it works on, such as{"linux", "darwin"}.method_type: the kind of lookup it does (see below).network_request: whether using it sends traffic on the network.
A method overrides two functions:
test(): a cheap check that the method can work on this system, such as “is theipcommand installed?”get(): performs the lookup. It takes one argument, and returns the result orNone. The argument’s meaning depends on the method, e.g. for an interface method, it would be the interface name (e.g."eth0").
Method types¶
|
Used for |
|
|
|---|---|---|---|
|
|
IPv4 address |
MAC address |
|
|
IPv6 address |
MAC address |
|
Both |
IPv4 or IPv6 address |
MAC address |
|
|
Interface name |
MAC address |
|
|
Empty string |
Interface name |
Note
get_mac_address() with no arguments does a default_iface lookup, then an iface lookup of the interface it finds. If the default interface can’t be found or it doesn’t have a MAC, the first interface from socket.if_nameindex() that has a MAC and isn’t a loopback interface is used instead, except on Windows.
On Windows with network_request=True (the default), it first gets the IP address of the interface with the default route from fetch_ip_using_dns(), and does an ip4 lookup of that address. The default_iface lookup is only done if that doesn’t find a MAC.
Note
There is one cache per lookup type: ip4, ip6, iface and default_iface.
Platforms¶
The platform is a lowercase identifier, consts.PLATFORM, unless you override it with settings.OVERRIDE_PLATFORM. To see what your system is detected as:
from getmac.variables import consts
print(consts.PLATFORM) # For example, "linux"
The identifiers used by the built-in methods are listed in Method.VALID_PLATFORM_NAMES, and Platforms lists the methods for each platform.
The platform "other" is used for methods that are generic enough to try on unknown systems, and are only used as a last resort if the current platform matches no method.
Choosing a method¶
The first time a lookup is performed for a particular type (e.g. ip4), the cache for that type is initialized by initialize_method_cache():
Selects methods in
METHODSwith a matchingmethod_type.Selects methods whose
platformsset includes the current platform, or"other"if nothing matches (see the section above).If
network_request=False, it excludes methods that havenetwork_request=True.Creates instances of the selected methods and calls their
test(). The first method that passes (returnsTrue) becomes the primary method, stored inMETHOD_CACHE[type]. The others that pass become fallbacks, stored in order inFALLBACK_CACHE[type]. Methods whosetest()returnsFalseor raises an exception are left out.
initialize_method_cache() will raise RuntimeError if:
No method has the requested type.
No method suits the platform, even after trying
"other".Every candidate method fails its
test().
Note
The cache is built lazily on first lookup and reused for the rest of the process’s life. Methods aren’t tested again, so later changes to METHODS, to OVERRIDE_PLATFORM, or to the system itself (such as installing a command) don’t affect a type whose cache is already built.
Falling back during a lookup¶
Each lookup calls get() on the primary method from the cache and:
If
get()returns a value, winner winner chicken dinner, that’s the result.If
get()returnsNone, the result isNone. The fallbacks are not tried.Nonemeans “not found”, for example “there’s no such interface”, not “this method doesn’t work”.If
get()raises an exception, or setsself.unusable = Trueand returnsNone, the method is removed from the cache. The first fallback becomes the primary method, and the lookup is retried with it using the same argument. The exception is logged as a warning, not raised.A
CalledProcessErrorwith exit code 1 is treated like returningNone, because many commands exit with 1 when the interface or host doesn’t exist. Any other exit code counts as a failure and leads to a fallback.A command that runs longer than
settings.COMMAND_TIMEOUTis stopped, and the method is treated like one that raised an exception.With
network_request=False, methods that send network requests (theirnetwork_requestattribute isTrue) are skipped, both for the lookup and as fallbacks. They stay in the cache, since the cache may have been built by a lookup that allowed them.
IPv4 lookups and network requests¶
When get_mac_address() looks up an IPv4 address (ip= or hostname=) with network_request=True (the default), it first tries to make sure the host is in the system’s ARP table:
If
ArpFileis in theip4cache, it’s tried first, since reading/proc/net/arpis fast. If it fails, it’s removed from the cache, but no other method is tried yet. If it finds the host, nothing is sent on the network.Then, if the host wasn’t found and
CtypesHostorArpingHostis in theip4cache, it’s made the primary method, since it sends an ARP request itself.If neither applies, an empty UDP packet is sent to the host on the port specified by
settings.PORTto force the system to populate the ARP table.
Then the host is looked up with the ip4 cache. If the UDP packet was sent and the host isn’t found, it’s looked up again until it’s found or settings.ARP_TIMEOUT seconds have passed (by default, it isn’t looked up again). IPv6 lookups send the UDP packet and use ARP_TIMEOUT the same way, but there’s no ArpFile or ARP request step.
Seeing which methods are used¶
Inspecting the caches¶
After a lookup, the caches show which methods were chosen. Converting a method instance to a string with str gives its class name.
from getmac import get_mac_address
from getmac.getmac import FALLBACK_CACHE, METHOD_CACHE
# Force caches to be populated
get_mac_address()
# Print the name of each method in the cache
for method_type, method in METHOD_CACHE.items():
fallbacks = [str(m) for m in FALLBACK_CACHE[method_type]]
print(f"{method_type}: {method!s}, fallbacks: {fallbacks}")
Example output on a Linux system:
ip4: None, fallbacks: []
ip6: None, fallbacks: []
iface: SysIfaceFile, fallbacks: ['FcntlIface', 'IpLinkIface']
default_iface: DefaultIfaceLinuxRouteFile, fallbacks: ['DefaultIfaceIpRoute']
Two helper functions look methods up by name:
get_instance_from_cache()returns the cached instance of a method, primary or fallback, for one lookup type. The name must match the class name exactly, for exampleget_instance_from_cache("iface", "SysIfaceFile").get_method_by_name()returns the class with a given name fromMETHODS, ignoring case. This is howFORCE_METHODfinds a method.
Logging and debug output¶
getmac logs to the getmac logger with Python’s logging module, and settings.DEBUG controls how much detail is logged (the attribute’s documentation describes the levels). Level 2 is the one to use to see how methods were chosen:
import logging
from getmac import get_mac_address, settings
logging.basicConfig(format="%(levelname)-8s %(message)s", level=logging.DEBUG)
settings.DEBUG = 2
get_mac_address(interface="lo")
Example output on Linux, shortened:
DEBUG Initializing 'iface' method cache (platform: 'linux')
DEBUG 13 type-filtered methods for 'iface': SysIfaceFile, FcntlIface, LanscanIface, ...
DEBUG 6 platform-filtered methods for 'linux' (method_type='iface'): SysIfaceFile, ...
DEBUG Test failed for method 'IfconfigWithIfaceArg'
DEBUG Test failed for method 'IfconfigOther'
DEBUG Test failed for method 'NetstatIface'
DEBUG 3 tested methods for 'iface': SysIfaceFile, FcntlIface, IpLinkIface
...
DEBUG Attempting get() (method='SysIfaceFile', method_type='iface', arg='lo')
DEBUG Raw MAC found: 00:00:00:00:00:00
The command-line equivalent is getmac -v -dd -i lo, see Command-Line Interface.
Calling lookups directly¶
get_by_method()¶
get_by_method() does one lookup of a given type (e.g., "ip4") using the caches and fallbacks described above.
It returns whatever the method’s get() returned, without the clean-up that get_mac_address() does. Many built-in methods return the MAC the way the command printed it, so pass the result through clean_mac() to get a lowercase, colon-separated MAC (aka what is normally returned from get_mac_address()).
from getmac import utils
from getmac.getmac import get_by_method
raw = get_by_method("iface", "lo")
print(repr(raw))
print(utils.clean_mac(raw))
Example output on Linux:
'00:00:00:00:00:00\n'
00:00:00:00:00:00
A few more things to know:
An empty argument returns
Noneand logs an error, except fordefault_ifacetype methods, which take no argument.It raises
RuntimeErrorwhen no method can be used, as described in Choosing a method.Its
network_requestargument is passed toinitialize_method_cache()when that type’s cache is first built. It’s also applied on every later lookup, where methods that send network requests are skipped, both as the primary method and as fallbacks (see Falling back during a lookup).
get_default_interface()¶
get_default_interface() is get_by_method("default_iface"), so it can also raise RuntimeError. It doesn’t change the default interface that get_mac_address() remembers between calls (gvars.DEFAULT_IFACE).
from getmac import get_default_interface
try:
print(get_default_interface())
except RuntimeError as err:
print(err)
Settings¶
The settings are described in Configuration. Two of them change which methods are used, and this section adds how they interact with method selection.
FORCE_METHODThe name of a method to use for every lookup, e.g.
"IpLinkIface". The name is looked up inMETHODS, ignoring case. If no method matches, the lookup logs an error and returnsNone. On the command line, use--force-method. Thefull rulesare in the attribute’s documentation, and these are the parts that matter for method selection:A new instance is created for each lookup, and
test()is never called.platforms,method_typeandnetwork_requestare ignored, and the caches aren’t used or changed.There’s no fallback, and exceptions raised by the method are not caught.
It applies to every lookup type, including
get_mac_address()called with no arguments.For an IPv4 lookup with
network_request=True,get_mac_address()still goes through the steps in IPv4 lookups and network requests before calling the forced method, so theip4cache is still built, and the UDP packet is still sent (unless the forced method is"CtypesHost"or"ArpingHost"and it’s in theip4cache, i.e. it passed its test, since they send an ARP request themselves; otherwise the UDP packet is still sent). If"ArpFile"is forced and the cachedArpFileinstance finds the MAC in step 1, that’s returned, and the forced method is never called.
OVERRIDE_PLATFORMOverride the detected platform identifier to whatever you set, e.g.
"linux". Use--override-platformon the command line. It’s only read when a cache is built, so set it before the first lookup or reset the caches afterwards. It only changes which methods are chosen. Other platform-specific behavior inget_mac_address(), such as how the default interface is found on Windows, still follows the detected platform.
Customizing methods¶
To add your own method, remove a built-in one, or undo your changes in tests, see Customizing methods at runtime.