Get MAC addresses of remote hosts and local interfaces
Pure-Python package to get the MAC address of network interfaces and hosts on the local network.
It provides a platform-independent interface to get the MAC addresses of:
- System network interfaces (by interface name)
- Remote hosts on the local network (by IPv4/IPv6 address or hostname)
It provides one function:
Should you use this package?
If you only need the addresses of network interfaces, have a limited set of platforms to support, and are able to handle C-extension modules, then you should instead check out the excellent netifaces package by Alastair Houghton (@al45tair). It's significantly faster (thanks to it being C-code) and has been around a long time and seen widespread usage. However, unfortunately it is no longer maintained as of May 2021, so it may not be a great choice for new projects. Another great option that fits these requirements is the well-known and battle-hardened psutil package by Giampaolo Rodola.
If the only system you need to run on is Linux, you can run as root, and C-extensions modules are fine, then you should instead check out the arpreq package by Sebastian Schrader. In some cases it can be significantly faster.
If you want to use
netifaces, I have examples of how to do so in a GitHub Gist.
Stable release from PyPI
pip install getmac
Latest development version
pip install https://github.com/ghostofgoes/getmac/archive/main.tar.gz
from getmac import get_mac_address eth_mac = get_mac_address(interface="eth0") win_mac = get_mac_address(interface="Ethernet 3") ip_mac = get_mac_address(ip="192.168.0.1") ip6_mac = get_mac_address(ip6="::1") host_mac = get_mac_address(hostname="localhost") updated_mac = get_mac_address(ip="10.0.0.1", network_request=True) # Enable debugging from getmac import getmac getmac.DEBUG = 2 # DEBUG level 2 print(getmac.get_mac_address(interface="Ethernet 3")) # Change the UDP port used for updating the ARP table (UDP packet) from getmac import getmac getmac.PORT = 44444 # Default is 55555 print(getmac.get_mac_address(ip="192.168.0.1", network_request=True))
Python 2 users: use
python -m getmac instead of
getmac --help getmac --version # Invoking with no arguments will return MAC of the default interface getmac # Usage as a module python3 -m getmac # Interface names, IPv4/IPv6 addresses, or Hostnames can be specified getmac --interface ens33 getmac --ip 192.168.0.1 getmac --ip6 ::1 getmac --hostname home.router # Running as a Python module with shorthands for the arguments python -m getmac -i 'Ethernet 4' python -m getmac -4 192.168.0.1 python -m getmac -6 ::1 python -m getmac -n home.router # Getting the MAC address of a remote host requires the ARP table to be populated. # By default, getmac will populate the table by sending a UDP packet to a high port on the host (defaults to 55555). # This can be disabled with --no-network-request, as shown here: getmac --no-network-request --ip 192.168.0.1 python -m getmac --no-network-request -n home.router # Enable output messages getmac --verbose # Debug levels can be specified with '-d' getmac -v --debug python -m getmac -v -d -i enp11s4 python -m getmac -v -dd -n home.router # Change the UDP port used for populating the ARP table when getting the MAC of a remote host getmac --ip 192.168.0.1 --override-port 9001 # The platform detected by getmac can be overridden via '--override-platform'. # This is useful when debugging issues or if you know a method # for a different platform works on the current platform. # Any values returned by platform.system() are valid. getmac -i eth0 --override-platform linux getmac --ip 192.168.0.1 --override-platform windows # Force a specific method to be used, regardless of the consequences or if it even works getmac -v -dddd --ip 192.168.0.1 --force-method ctypeshost
interface: Name of a network interface on the system
ip: IPv4 address of a remote host
ip6: IPv6 address of a remote host
hostname: Hostname of a remote host
network_request: If an network request should be made to update and populate the ARP/NDP table of remote hosts used to lookup MACs in most circumstances. Disable this if you want to just use what's already in the table, or if you have requirements to prevent network traffic. The network request is a empty UDP packet sent to a high port,
55555by default. This can be changed by setting
getmac.PORTto the desired integer value. Additionally, on Windows, this will send a UDP packet to
184.108.40.206:53to attempt to determine the default interface (Note: the IP is CloudFlare's DNS server).
logging.getLogger("getmac"): Runtime messages and errors are recorded to the
getmaclogger using Python's logging module. They can be configured by using logging.basicConfig() or adding handlers to the
getmac.getmac.DEBUG: integer value that controls debugging output. The higher the value, the more output you get.
getmac.getmac.PORT: UDP port used to populate the ARP/NDP table (see the documentation of the
getmac.getmac.OVERRIDE_PLATFORM: Override the platform detection with the given value (e.g.
"freebsd", etc.'). Any values returned by
getmac.getmac.FORCE_METHOD: Force a specific method to be used, e.g. 'IpNeighborShow'. This will be used regardless of it's method type or platform compatibility, and
Method.test()will NOT be checked! The list of available methods is in
- Pure-Python (no compiled C-extensions required!)
- Python 2.7 and 3.4+
- Lightweight, with no dependencies and a small package size
- Can be dropped into a project as a standalone .py file
- Supports most interpreters: CPython, pypy, pypy3, IronPython 2.7, and Jython 2.7
- Provides a simple command line tool (when installed as a package)
- MIT licensed!
Legacy Python versions
If you are running a old Python (2.6/3.3 and older) or interpreter, then you can install an older version of
getmac that supported that version. The wheels are available in the GitHub releases, or from PyPI with a current version of
pip and some special arguments.
- Python 2.5: get-mac 0.5.0
- Python 2.6: getmac 0.6.0
- Python 3.2: get-mac 0.3.0
- Python 3.3: get-mac 0.3.0
NOTE: these versions do not have many of the performance improvements, platform support, and bug fixes that came with later releases. They generally work, just not as well. However, if you're using such an old Python, you probably don't care about all that :)
- Python 3.10 and 3.11 should work, but are not automatically tested at the moment due to having to support 2.7
- If none of the arguments are selected, the default network interface for the system will be used. If the default network interface cannot be determined, then it will attempt to fallback to typical defaults for the platform (
en0on OSX/Darwin, and
eth0otherwise). If that fails, then it will fallback to
loon POSIX systems.
- "Remote hosts" refer to hosts in your local layer 2 network, also commonly referred to as a "broadcast domain", "LAN", or "VLAN". As far as I know, there is not a reliable method to get a MAC address for a remote host external to the LAN. If you know any methods otherwise, please open a GitHub issue or shoot me an email, I'd love to be wrong about this.
- The first four arguments are mutually exclusive.
network_requestdoes not have any functionality when the
interfaceargument is specified, and can be safely set if using in a script.
- The physical transport is assumed to be Ethernet (802.3). Others, such as Wi-Fi (802.11), are currently not tested or considered. I plan to address this in the future, and am definitely open to pull requests or issues related to this, including error reports.
- Exceptions will be handled silently and returned as a None. If you run into problems, you can set
DEBUGto true and get more information about what's happening. If you're still having issues, please create an issue on GitHub and include the output with
Commands and techniques by platform
- Default interfaces:
ip route list
- Mac OSX (Darwin)
- Same commands as Linux
- Windows commands are used for remote hosts
- Unix commands are used for interfaces
- Default interfaces:
- Default interfaces:
Platforms currently supported
All or almost all features should work on "supported" platforms. While other versions of the same family or distro may work, they are untested and may have bugs or missing features.
- Desktop: 7, 8, 8.1, 10, 11 (thanks @StevenLooman for testing Windows 11!)
- Server: TBD
- Partially supported (untested): 2000, XP, Vista
- Linux distros
- CentOS/RHEL 6+
- Ubuntu 16.04+ (15.10 and older should work, but are untested)
- Fedora (24+)
- Mac OSX (Darwin)
- The latest two versions probably (TBD)
- Android (6+)
- Windows Subsystem for Linux (WSL)
- FreeBSD (11+)
-v /proc/1/net/arp:/host/arp -e ARP_PATH=/host/arp to access arp table of host inside container in bridge network mode.
docker build -f packaging/Dockerfile -t getmac . docker run -it getmac:latest --help docker run -it getmac:latest --version docker run -it getmac:latest -n localhost docker run --rm -it -v /proc/1/net/arp:/host/arp -e ARP_PATH=/host/arp getmac:latest -n 192.168.0.1
- Depending on the platform, there could be a performance detriment, due to heavy usage of regular expressions.
- Platform test coverage is imperfect. If you're having issues, then you might be using a platform I haven't been able to test. Keep calm, open a GitHub issue, and I'd be more than happy to help.
- Linux, WSL: Getting the mac of a local interface IP does not currently work (
getmac --ip 10.0.0.4will fail if
10.0.0.4is the IP address of a local interface). This issue may be present on other POSIX systems as well.
- Hostnames for IPv6 devices are not yet supported.
- Windows: the "default" (used when no arguments set or specified) of selecting the default route interface only works effectively if
network_requestis enabled. If not,
Ethernetis used as the default.
- IPv6 support is good but lags behind IPv4 in some places and isn't as well-tested across the supported platform set.
Background and history
The Python standard library has a robust set of networking functionality, such as
ssl, and more. Imagine my surprise, then, when I discovered there was not a way to get a seemingly simple piece of information: a MAC address. This package was born out of a need to get the MAC address of hosts on the network without needing admin permissions, and a cross-platform way get the addresses of local interfaces.
In Fall 2018 the package name changed to
get-mac. This affected the package name, the CLI script, and some of the documentation. There were no changes to the core library code. While both package names will updated on PyPI, the use of
getmac is preferred.
In Summer 2020, the code was significantly refactored, moving to a class-based structure and significantly improving performance and accuracy. See docs/rewrite.md for details.
Before submitting a PR, please make sure you've completed the pull request checklist!
The Python Discord server is a good place to ask questions or discuss the project (Handle: @KnownError#0001).
- Christopher Goes (@ghostofgoes) - Author and maintainer
- Calvin Tran (@cyberhobbes) - Windows interface detection improvements
- Daniel Flanagan (@FlantasticDan) - Code cleanup
- @emadmahdi - Android fixes
- Izra Faturrahman (@Frizz925) - Unit tests using the platform samples
- Jose Gonzalez (@Komish) - Docker container and Docker testing
- @fortunate-man - Awesome usage videos
- @martmists - legacy Python compatibility improvements
- @hargoniX - scripts and specfiles for RPM packaging
- Ville Skyttä (@scop) - arping lookup support
- Tomasz Duda (@tomaszduda23) - support for docker in network bridge mode
- Steven Looman (@StevenLooman) - Windows 11 testing
Many of the methods used to acquire an address and the core logic framework are attributed to the CPython project's UUID implementation.
Other notable sources
MIT. Feel free to copy, modify, and use to your heart's content. Enjoy :)
NOTE: if any changes significantly impact your project or use case, please open an issue on GitHub or email me (see git commit author info for address).
Announcement: Compatibility with Python versions older than 3.7 (2.7, 3.4, 3.5, and 3.6) is deprecated and will be removed in getmac 1.0.0. If you are stuck on an unsupported Python, consider loosely pinning the version of this package in your dependency list, e.g.
- Fix flakyness with UuidArpGetNode on MacOS by making it the last method attempted (Fixes issue #82)
- Deprecate Python 3.6 support (support will be removed in getmac 1.0.0)
- Fix links in README and PyPI metadata to use "main" instead of "master" for primary branch
- Remove "Documentation" link from PyPI (the ReadTheDocs site is broken and hasn't been updated since 0.5.0)
- Add PyPI classifiers for 3.10 and 3.11
- Some cleanup of CHANGELOG
This release is a complete rewrite of getmac from the ground up. The public API of
getmac is unchanged as part of this rewrite.
get_mac_address() is still the primary way of getting a MAC address, it's just the "under the hood" internals that have changed completely.
It's passing tests and seems to be operable. However, with a change this large there are inevitably issues that the tests or I don't catch, so I'm doing a series of pre-releases until I'm 99% confident in it's stability. Refer to
docs/rewrite.md for a in-depth explanation of the rewrite changes.
The new system has a number of benefits
- Reduction of false-positives and false-negatives by improving method selection accuracy (platform, validity, etc.)
- Significantly faster overall
- "Misses" have the same performance as "Hits"
- Easier to test, since each method can be tested directly via it's class
- Easier to type annotate and analyze with mypy
- Easier to read, improving reviewability and ease of contributing for newcomers
- Extensible! Custom methods can be defined and added at runtime (which is perfect if you have some particular edge case but aren't able to open-source it).
- Fully support Python 3.9 (automated tests in CI)
- Tentatively support Python 3.10 and 3.11 (unable to test due to the need to be able to still test 2.7)
- Added default interface detection for MacOS (command:
route get default)
- Added initial support for Solaris/SunOS. There were a few existing methods that worked as-is, so just added indicators that those methods support
sunos(Which applies to any system where
platform.system() == SunOS).
SendARP(Windows) will now always be used instead of sending a UDP packet when looking for the MAC of a IPv4 host, if they're available and operable (otherwise, UDP + ARP table check will be used like before).
- The amount of time taken to get a result (in seconds) will now be recorded and logged if debugging is enabled (
- Added command line argument to override the UDP port for network requests:
--override-port(this was already possible in Python via
getmac.getmac.PORT, but wasn't configurable via the CLI. Now it is!).
- Added ability to override the detected platform via
--override-platformargument (CLI) or
getmac.getmac.OVERRIDE_PLATFORMvariable (Python). This will force methods for that platform to be used, regardless of the actual platform. Here's an example forcing
linuxto be used as the platform:
getmac -i eth0 --override-platform linux. In version 1.0.0, this feature will added as an argument to
- Added ability to force a specific method to be used via
--force-methodargument (CLI) or
getmac.getmac.FORCE_METHODvariable (Python). This is useful for troubleshooting issues, general debugging, and testing changes. Example:
getmac -v -dddd --ip 192.168.0.1 --force-method ctypeshost
- Complete rewrite of
getmacfrom the ground up. Refer to
docs/rewrite.mdfor a in-depth explanation of the rewrite changes
- Fixed a failure to look up a hostname now returns
None, as expected, instead of raising an exception (
- Fixed numerous false-negative and false-positive bugs
- Improved overall performance
- Performance for cases where no MAC is found is now the same as cases where a MAC is found (speed of "misses" now equals that of "hits")
- Improved the reliability and performance of many methods
netstaton older Linux distros (such as Ubuntu 12.04)
ifconfigparsing. It should now be far more reliable and accurate across all platforms.
- Improved Android support. Note that newer devices are locked down and the amount of information that's obtainable by an unprivileged process is quite limited (Android 7/9 and newer, not sure exactly when they changed this, I'm not an Android guy). That being said, the normal Linux methods should work fine, provided you have the proper permissions (usually,
- Fixed bug with
/proc/net/routeparsing (this affected Android and potentially other platforms)
- Improve default interface detection for FreeBSD (command:
route get default)
- Removed man pages from distribution (
getmac2.1). They were severely out of date and unused. May re-add at a later date.
- Migrate CI to GitHub Actions, remove TravisCI and Appveyor
- Add flake8 plugins:
- Add additional samples and tests for WSL1 (with the Ubuntu 18.04 distro)
- Add additional samples for Windows 10
- Add additional samples for MacOS
- Add samples and tests for Ubuntu 12.04
- Add samples for NetBSD 8 (support coming in a future release)
- Add samples for Solaris 10 (support TBD)
- Add samples for several versions of Android
- Add new tests
- Improve existing tests
- Consolidate everything related to RPM packaging to
packaging/rpm/. This stuff hasn't been updated since 0.6.0, may remove in the future and leave distro packaging to distro maintainers.
- Added support for Thomas Habets' version of
arpingin addition to the existing iputils one (contributed by Ville Skyttä (@scop) in #52 and #54)
- Added support for docker in network bridge mode (contributed by Tomasz Duda (@tomaszduda23) in #57)
- Add CHANGELOG URL to PyPI metadata (contributed by Ville Skyttä (@scop) in #58)
- Fixed code quality test suite errors (includes changes by Daniel Flanagan (@FlantasticDan) in #67)
- Improved Android support (contributed by @emadmahdi in #71)
- Minor code quality fixes (2 years of neglecting master branch)
- Add Code of Conduct for project contributors
- Add SECURITY.md for reporting security issues (e.g. vulnerabilities)
- Deprecate Python 3.4 and 3.5
- Issue deprecation message as a warning in addition to a log message
- Added warning about Python 2 compatibility being dropped in 1.0.0
- Officially support Python 3.8
- Documented a known issue with looking up IP of a local interface on Linux/WSL (See the "Known Issues" section in the README)
- Added remote host lookup using
arpingas last resort
- Standardized formatting on Black
- Lint additions:
vulture, several Flake8 plugins
- Pinned test dependencies (pytest 5 dropped Python 2 support)
- Various quality-of-life improvements for contributors/developers
- Fixed sockets being opened and not closed when
ip6were used, which could lead to a
- OpenBSD support
- FreeBSD support
- Python logging is now used instead of
- Include tests in the source distribution
- (CLI) Added aliases for
- (CLI) New argument:
- Errors are now logged instead of raising a
- Improved Ubuntu support
- Performance improvements
- Significant increase in overall test coverage
- Fixed and migrated the sample tests to
- Added tests for the CLI
- Type annotations (PEP 484)
- Dropped support for Python 2.6
- Removed the usage of third-party packages (
arpreq). This should improve the performance of lookups of non-existent interfaces or hosts, since this feature was punishing that path without providing much value. If you want to use these packages directly, I have a guide on how to do so on a GitHub Gist.
- Significantly improved the performance of the common cases on Linux for interfaces and remote hosts
- Improved POSIX interface performance. Commands specific to OSX will be run only on that platform, and vice-versa.
- Significantly improved the speed and accuracy of determining the default interface on Linux
- Python 2 will install an executor named getmac2 and Python 3 an executor named getmac so they do not conflict when both RPMs are installed on the same system (Credit: @hargoniX)
warningsmodule will only be imported if a error/warning occurs (improve compatibility with some freezers, notably PyInstaller)
- Improved system platform detection
- Various other minor performance improvements
- Added unit tests for the samples (Credit: @Frizz925)
- Scripts for building RPMs in the /scripts directory (Credit: @hargoniX)
- Improved code quality and health checks
- Include the CHANGELOG on the PyPI project page
pytestfor all tests now instead of
- Added instructions on how to build a Debian package (Credit: @kofrezo)
- Windows default interface detection if
network_requestis enabled (Credit: @cyberhobbes)
- Docker container (Credit: @Komish)
- Changed project name to
getmac. This applies to the command line tool, GitHub, and the documentation.
- Use proper Python 2-compatible print functions (Credit: @martmists)
- Support for Python 2.5. It is not feasible to test, and potentially
breaks some useful language features, such as
- Variables PORT and DEBUG from top-level package imports, since changing
them would have no actual effect on execution. Instead, use
- Added example videos demonstrating usage (Credit: @fortunate-man)
- Added contribution guide
- Added documentation on ReadTheDocs
- Added a manpage
- Full support for Windows Subsystem for Linux (WSL). This is working for all features, including default interface selection! The only edge case is lookup of remote host IP addresses that are actually local interfaces will not resolve to a MAC (which should be ff-ff-ff-ff-ff-ff).
argparseif Python version is 2.6 or older
- Updated tox tests: added Jython and IronPython, removed 2.6
- New methods for remote host MACs
- New methods for interface MACs
- DEBUG levels: DEBUG value is now an integer, and increasing it will increase the amount and verbosity of output. On the CLI, it can be configured by increasing the amount of characters for the debug argument, e.g. '-dd' for DEBUG level 2.
- Jython support (Note: on Windows Jython currently only works with interfaces)
- IronPython support
- Significant performance improvement for remote hosts. Previously,
the average for
get_mac_address(ip='10.0.0.100')was 1.71 seconds. Now, the average is
12.7 miliseconds, with the special case of a unpopulated arp table being only slightly higher. This was brought about by changes in how the arp table is populated. The original method was to use the host's
pingcommand to send an ICMP packet to the host. This took time, which heavily delayed the ability to actually get an address. The solution is to instead simply send a empty UDP packet to a high port. The port this packet is sent to can be configured using the module variable
- "Fixed" resolution of localhost/127.0.0.1 by hardcoding the response. This should resolve a lot of problematic edge cases. I'm ok with this for now since I don't know of a case when it isn't all zeroes.
- Greatly increased the reliability of getting host and interface MACs on Windows
- Improved debugging output
- Tightened up the size of
- Various minor stability and performance improvements
- Add LICENSE to PyPI package
- Support for Python 3.2 and 3.3. The total downloads from PyPI with those versions in August was ~53k and ~407K, respectfully. The majority of those are likely from automated testing (e.g. TravisCI) and not actual users. Therefore, I've decided to drop support to simplify development, especially since before 3.4 the 3.x series was still very much a "work in progress".
- Added automated tests for Windows using Appveyor
- Tox runner for tests
- Added github.io page
- Improved TravisCI testing
- Attempt to use Python modules if they're installed. This is useful
for larger projects that already have them installed as dependencies,
as they provide a more reliable means of getting information.
psutil: Interface MACs on all platforms
scapy: Interface MACs and Remote MACs on all platforms
netifaces: Interface MACs on Non-Windows platforms
- New methods for remote MACs
ip neighbor show, Abuse of
- New methods for Interface MACs
- Certain critical failures that should never happen will now warn instead of failing silently.
- Added a sanity check to the
ip6argument (IPv6 addresses)
- Improved performance in some areas
- Improved debugging output
- Major Bugfix: search of
proc/net/arpwould return shorter addresses in the same subnet if they came earlier in the sequence. Example: a search for
192.168.16.2on Linux would instead return the MAC address of
192.168.16.254with no errors or warning whatsoever.
- Significantly improved default interface detection. Default
interfaces are now properly detected on Linux and most other
POSIX platforms with
routecommands available, or the
- Vagrantfile to spin up testing VMs for various platforms using Vagrant
- Added more samples of command output on platforms (Ubuntu 18.04 LTS)
- Fixed identification of remote host on OSX
- Resolved hangs and noticeable lag that occurred when "network_request" was True (the default)
- Remote host for Python 3 on Windows
- Short versions of CLI arguments (e.g. "-i" for "--interface")
- Improved usage of "ping" across platforms and IP versions
- Various minor tweaks for performance
- Improved Windows detection
- Use of ping command with hostname
- Improvements to internal code
Nothing changed. PyPI just won't let me push changes without a new version.
- Checks for default interface on Linux systems
- New methods of hunting for addresses on Windows, Mac OS X, and Linux
- CLI will output nothing if it failed, instead of "None"
- CLI will return with 1 on failure, 0 on success
- No CLI arguments now implies the default host network interface
- Added an argumnent for debugging:
- Interfaces on Windows and Linux (including Bash for Windows)
- Many bugs
- Support for Python 2.6 on the CLI
- Overhaul of internals
- Addition of a terminal command:
- Ability to run as a module from the command line:
python -m getmac
arp_requestargument was renamed to
- Updated docstring
- Slight reduction in the size of getmac.py
- Overhauled the README
- Moved tests into their own folder
- Added Python 3.7 to list of supported snakes
- Python 2.6 compatibility
- Fixed some addresses returning without colons
- Added more rigorous checks on addresses before returning them
- Remove print statements and other debugging output
- Initial pre-alpha
Release history Release notifications | RSS feed
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.