Last active
October 24, 2020 11:01
-
-
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
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
#!/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