-
-
Save MaurizioCasciano/65ac71e2ba6efa676c323f990ce81363 to your computer and use it in GitHub Desktop.
Get MAC addresses using a variety of Python packages.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ************************************** | |
# ** Get MAC address of a remote host ** | |
def arpreq_ip(ip): | |
# type: (str) -> Optional[str] | |
import arpreq | |
return arpreq.arpreq('192.168.1.1') | |
def scapy_ip(ip): | |
# type: (str) -> str | |
"""Requires root permissions on POSIX platforms. | |
Windows does not have this limitation.""" | |
from scapy.layers.l2 import getmacbyip | |
return getmacbyip(ip) | |
# ****************************************** | |
# ****************************************** | |
# ** Get MAC address of a local interface ** | |
def psutil_iface(iface): | |
# type: (str) -> Optional[str] | |
import psutil | |
nics = psutil.net_if_addrs() | |
if iface in nics: | |
nic = nics[iface] | |
for i in nic: | |
if i.family == psutil.AF_LINK: | |
return i.address | |
def netifaces_iface(iface): | |
# type: (str) -> str | |
import netifaces | |
return netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'] | |
def scapy_iface(iface): | |
# type: (str) -> str | |
from scapy.layers.l2 import get_if_hwaddr | |
if WINDOWS: | |
from scapy.arch.windows import get_windows_if_list | |
interfaces = get_windows_if_list() | |
for i in interfaces: | |
if any(iface in i[x] for x in | |
['name', 'netid', 'description', 'win_index']): | |
return i['mac'] | |
# WARNING: Do not put an 'else' here! | |
return get_if_hwaddr(iface) | |
# ******************************************** | |
# ******************************************** | |
# Determine the default interface for a system | |
def netifaces_default_gateway(): | |
# type: () -> str | |
import netifaces | |
return list(netifaces.gateways()['default'].values())[0][1] | |
# ******************************************** |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment