Python 100 project #28: Gateway MAC address getter

I thought it’s quite easy to get the default gateway information from PCs or MAC. But found out it was quite tough, it really depends on OS platform. So I ended up using third party library “netifaces“, which is quite easy to use to retrieve local address information. This time I created a small function to retrieve default gateway MAC address.

Output Example:

$ python3 

Here is the code:

import re
import subprocess

import netifaces

def get_dgw():

    return netifaces.gateways()['default'][netifaces.AF_INET][0]

def get_macaddr(ipaddr):

    # to generate first packet (if not any yet) so that it resolves mac address of ipaddr
    subprocess.Popen(["ping", "-c 1", ipaddr], stdout=subprocess.PIPE)

    data = subprocess.Popen(["arp", "-a"], stdout=subprocess.PIPE)
    arp_table = data.communicate()[0]
    arp_entries = str(arp_table,'utf-8').split("\n")

    for entry in arp_entries:
        if f"({ipaddr})" in entry:
            return"([a-f\d]{1,2}:){5}[a-f\d]{1,2}", entry).group()

    return False

if __name__ == "__main__":
    dgw = get_dgw()
    dgw_mac = get_macaddr(dgw)
    if dgw_mac:
        print("Something goes wrong...")