Python script to get device vendor name from MAC Address


In the world of networking, MAC addresses play a crucial role in identifying devices connected to a network. A MAC (Media Access Control) address is a unique identifier assigned to each network interface card (NIC) or network adapter. It consists of six groups of two hexadecimal digits, separated by colons or hyphens. MAC addresses are commonly used for various purposes, including network management, security, and troubleshooting.

In this article, we will explore how to create a Python script to retrieve the device vendor name from a given MAC address. We will explore two approaches: using an API to query a MAC address vendor database and using a local MAC vendor database. By leveraging Python's capabilities and relevant APIs, we can automate the process and obtain the vendor name with ease.

Understanding MAC Addresses

Before we proceed with retrieving the device vendor name from a MAC address, let's take a moment to understand the structure and significance of MAC addresses in networking.

MAC Address Structure

A MAC address consists of 48 bits (6 bytes) represented in hexadecimal notation. It is typically written as six groups of two hexadecimal digits separated by colons or hyphens. For example, 00:1A:2B:3C:4D:5E or 00-1A-2B-3C-4D-5E. The first three groups of the MAC address are known as the Organizationally Unique Identifier (OUI) and represent the device vendor or manufacturer. The last three groups are the device-specific identifier.

Importance of MAC Addresses

MAC addresses are essential for several networking tasks, including 

  • Address Resolution Protocol (ARP)  MAC addresses are used in the ARP process to map IP addresses to physical MAC addresses on local networks.

  • Switching and Bridging  Network switches and bridges use MAC addresses to determine the destination of data packets within a local network.

  • DHCP  MAC addresses are used by Dynamic Host Configuration Protocol (DHCP) servers to assign IP addresses to network devices.

  • Network Security  MAC addresses can be used for access control, allowing or denying network access based on device MAC addresses.

Understanding the significance of MAC addresses helps us appreciate the importance of retrieving device vendor names from them. It allows us to identify the manufacturer or organization associated with a particular MAC address, providing valuable information for network management and troubleshooting.

Next, we will explore two approaches to retrieve the device vendor name using Python.

Retrieving Device Vendor Name Using MAC Address API

To retrieve the device vendor name from a MAC address, we can leverage MAC address vendor lookup APIs. These APIs provide a database of MAC address ranges associated with device vendors and allow us to query the database using a MAC address.

Step 1: Install the Required Libraries

To make API requests and process the response, we need to install the requests library. Open your terminal or command prompt and run the following command −

pip install requests

Step 2: Import the Required Libraries

In your Python script, import the requests library 

import requests

Step 3: Make the API Request

We will use the "macaddress.io" API, which provides a free tier for MAC address vendor lookup. To use this API, sign up for a free account at https://macaddress.io/ and obtain an API key.

mac_address = "00:1A:2B:3C:4D:5E"
api_key = "YOUR_API_KEY"

url = f"https://api.macaddress.io/v1?apiKey={api_key}&output=json&search={mac_address}"
response = requests.get(url)

Replace "YOUR_API_KEY" with your actual API key obtained from macaddress.io.

Step 4: Process the API Response

Once we receive the response from the API, we can extract the vendor name from the JSON data 

if response.status_code == 200:
    data = response.json()
    vendor_name = data["vendorDetails"]["companyName"]
    print("Device Vendor Name:", vendor_name)
else:
    print("Failed to retrieve device vendor name.")

Ensure to handle error cases where the API request fails or returns an error status code.

By following these steps, you can retrieve the device vendor name associated with a MAC address using an API. However, it's worth noting that API usage may be subject to rate limits or require a paid subscription beyond the free tier.

In the next section, we will explore an alternative approach using a local MAC vendor database.

Using a Local MAC Vendor Database

Alternatively, instead of relying on an external API, you can use a local MAC vendor database to retrieve the device vendor name from a MAC address. This approach does not require making API requests and allows you to perform the lookup offline.

Step 1: Obtain a Local MAC Vendor Database

There are several open-source MAC vendor databases available that you can download and use. One popular option is the "OUI.txt" file provided by the IEEE Standards Association. This file contains a comprehensive list of MAC address prefixes and their associated vendor names.

You can download the "OUI.txt" file from the IEEE Standards Association website (https://standards.ieee.org/products-services/regauth/oui/). Ensure to read and comply with the licensing terms and conditions of the database you choose to use.

Step 2: Parse the MAC Vendor Database

Once you have the MAC vendor database file, you need to parse and load it into your Python script. Here's an example of how you can accomplish this 

mac_database_file = "path/to/OUI.txt"

mac_vendors = {}
with open(mac_database_file, "r") as f:
    for line in f:
        if "(hex)" in line:
            parts = line.strip().split("(hex)")
            mac_prefix = parts[0].strip()
            vendor_name = parts[1].strip()
            mac_vendors[mac_prefix] = vendor_name

This code reads the MAC vendor database file line by line, extracts the MAC address prefix and the associated vendor name, and stores them in a dictionary for efficient lookup.

Step 3: Retrieve Device Vendor Name

Now that we have the MAC vendor database loaded, we can retrieve the device vendor name using the MAC address 

mac_address = "00:1A:2B:3C:4D:5E"

mac_prefix = mac_address[:8].upper().replace(":", "")
vendor_name = mac_vendors.get(mac_prefix, "Unknown")

print("Device Vendor Name:", vendor_name)

We extract the first 6 bytes (8 characters) of the MAC address, convert them to uppercase, remove the colons, and use this as the key to look up the vendor name in the dictionary. If the MAC address prefix is found in the database, we retrieve the associated vendor name. Otherwise, we default to "Unknown".

By following these steps, you can retrieve the device vendor name from a MAC address using a local MAC vendor database. This approach offers offline functionality and does not require making API requests.

In the next section, we will discuss some considerations and potential improvements for the script.

Considerations and Potential Improvements

While the Python script we've developed is functional, there are some considerations and potential improvements to keep in mind:

Database Updates

MAC vendor databases are constantly evolving as new devices and vendors are added. It's important to periodically update your local MAC vendor database to ensure accurate results. You can visit the IEEE Standards Association website or other reliable sources to download the latest version of the database.

Error Handling

In the current implementation, if the MAC address is not found in the database, we default to "Unknown" as the vendor name. However, it's a good practice to implement appropriate error handling to handle scenarios where the MAC address is invalid or not present in the database. You can raise custom exceptions or return meaningful error messages to enhance the script's robustness.

Caching

If you frequently need to look up vendor names for MAC addresses, you can consider implementing a caching mechanism. This can help improve performance by storing previously looked-up MAC addresses and their associated vendor names. You can use a caching library like cachetools or even a simple dictionary to implement the caching functionality.

User Input Validation

When accepting user input for MAC addresses, it's essential to validate and sanitize the input to ensure it conforms to the expected format. You can use regular expressions or string manipulation techniques to validate the MAC address format and handle variations like uppercase, lowercase, or mixed case input.

Error Logging

To aid in troubleshooting and debugging, consider implementing error logging within your script. This can help capture any unexpected errors or exceptions that occur during the execution of the script. Tools like the Python logging module can be used to log error messages to a file or the console.

In the next section, we'll provide a summary and conclusion for the article.

Conclusion

In this tutorial, we've explored how to create a Python script to retrieve the device vendor name from a MAC address. We used the requests library to fetch the MAC vendor database from a remote server and parsed the response to extract the vendor name based on the MAC address.

We covered the necessary steps to install the required libraries and walked through the implementation of the script. We also discussed considerations and potential improvements to enhance the script's functionality, such as updating the database, error handling, caching, input validation, and error logging.

By leveraging this script, you can easily retrieve the vendor name associated with a MAC address, which can be useful in various network-related applications and troubleshooting scenarios.

Updated on: 11-Aug-2023

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements