Skip to content

Instantly share code, notes, and snippets.

@EONRaider
Last active October 24, 2020 11:01
Show Gist options
  • Save EONRaider/f2284ccf75613c8751e20062b9e750f3 to your computer and use it in GitHub Desktop.
Save EONRaider/f2284ccf75613c8751e20062b9e750f3 to your computer and use it in GitHub Desktop.
Get the IP, MAC, netmask and broadcast addresses of a network interface in Python 3
#!/usr/bin/env python3
# https://gist.github.com/EONRaider/f2284ccf75613c8751e20062b9e750f3
__author__ = 'EONRaider, keybase.io/eonraider'
try:
import netifaces
except ModuleNotFoundError as e:
raise SystemExit(f"Requires {e.name} module. Run 'pip install {e.name}' "
f"and try again.")
def get_iface_info(interface: str) -> dict:
iface_info: dict = netifaces.ifaddresses(interface)
mac_addr: str = iface_info[netifaces.AF_LINK][0]['addr']
try:
inet_info: dict = iface_info[netifaces.AF_INET][0]
ip_addr, netmask, broadcast = inet_info.values()
except KeyError:
ip_addr = netmask = broadcast = None
return {'MAC': mac_addr,
'IP': ip_addr,
'Netmask': netmask,
'Broadcast': broadcast}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment