Python 100 project #29: MAC address to Vendor

I modified yesterdays code a bit and extended it with mac address to vendor translation.

Output Example:

$ python3 get_macvendor.py 
zte corporation

 

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 re.search(r"([a-f\d]{1,2}:){5}[a-f\d]{1,2}", entry).group()

    return False


def main():
    dgw = get_dgw()
    dgw_mac = get_macaddr(dgw)
    if dgw_mac:
        return dgw_mac
    else:
        return False


if __name__ == "__main__":
    dgw_mac = main()
    print(dgw_mac if dgw_mac else "Something went wrong...")
import requests


def get_macvendor(macaddr):
    base_url = "http://api.macvendors.com/"

    resp = requests.get(base_url + macaddr)

    return resp.text


if __name__ == "__main__":

    import get_dgwmacaddress
    print(get_macvendor(get_dgwmacaddress.main()))