Skip to content

Instantly share code, notes, and snippets.

@GhostofGoes
Last active November 13, 2023 13:00
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save GhostofGoes/0a8e82930e75afcefbd879a825ba4c26 to your computer and use it in GitHub Desktop.
Save GhostofGoes/0a8e82930e75afcefbd879a825ba4c26 to your computer and use it in GitHub Desktop.
Get MAC addresses using a variety of Python packages.
# **************************************
# ** 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