The Wayback Machine - https://web.archive.org/web/20240928143834/https://www.geeksforgeeks.org/extracting-mac-address-using-python/
Open In App

Extracting MAC address using Python

Last Updated : 29 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

MAC address also known as physical address is the unique identifier that is assigned to the NIC (Network Interface Card) of the computer. NIC helps in connection of a computer with other computers in the network. MAC address is unique for all the NIC’s. Uses of MAC address : 

  • Useful in places where IP address change frequently. Helps network admin. to get information regarding network traffic.
  • Helps us to configure which computers can be connected to our computers. By this way we can filter potential spam/virus attacks.
  • Helps in uniquely identifying computers from other computers around the world.

MAC-Address This article aims at extracting MAC address of computer using Python. Method 1 : using mac module To get the physical address of the device we use getmac module of Python.

>>>from getmac import get_mac_address as gma
>>>print(gma())
'3c:7e:94:8f:d0:34'

Method 2 : Using uuid.getnode() getnode() can be used to extract the MAC address of the computer. This function is defined in uuid module. The illustrated code given below shows how to generate a UUID for a given host, identified by its MAC address, using the uuid1() function. 

Python3




# Python Program to compute
# MAC address of host
# using UUID module
 
import uuid
 
# printing the value of unique MAC
# address using uuid and getnode() function
print (hex(uuid.getnode()))


Output :

0x163e990bdb

Drawback :

  • The visible drawback is that the output is not in the formatted form.

Method 3 : Using getnode() + format() [ for better formatting ] 

Python3




# Python 3 code to print MAC
# in formatted way.
 
import uuid
 
# joins elements of getnode() after each 2 digits.
 
print ("The MAC address in formatted way is : ", end="")
print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff)
for ele in range(0,8*6,8)][::-1]))


Output :

The MAC address in formatted way is : 00:16:3e:99:0b:db

Drawback :

  • This code appears to be complex.

Method 4 : Using getnode() + findall() + re() [ for reducing complexity ] 

Python3




# Python 3 code to print MAC
# in formatted way and easier
# to understand
 
import re, uuid
 
# joins elements of getnode() after each 2 digits.
# using regex expression
print ("The MAC address in formatted and less complex way is : ", end="")
print (':'.join(re.findall('..', '%012x' % uuid.getnode())))


Output :

The MAC address in formatted and less complex way is : 00:16:3e:99:0b:db

Method5: psutil

This code is using the psutil module to get the MAC addresses of all the network interfaces on the computer.

To install the psutil module, you can use the following command:

pip install psutil

The code first imports the psutil module and then uses the net_if_addrs() function to get a dictionary of all the network interfaces on the computer, along with their addresses. It then iterates over all the keys in the dictionary (which represent the names of the network interfaces) and checks if the interface has a valid MAC address. If it does, the code prints the name of the interface and its MAC address.
 

Python3




import psutil
 
# Iterate over all the keys in the dictionary
for interface in psutil.net_if_addrs():
    # Check if the interface has a valid MAC address
    if psutil.net_if_addrs()[interface][0].address:
        # Print the MAC address for the interface
        print(psutil.net_if_addrs()[interface][0].address)
        break


Output:  00-FF-8F-73-83-9F
 



Similar Reads

Why is the IP address called a "logical" address, and the MAC address is called a "physical" address?
Let us try to deeply understand, why IP address is known as "Logical" while, MAC Address is known as "Physical" address. The IP address and the MAC address are both used for addressing and identifying devices on a computer network, but they serve different purposes and operate at different levels of the network stack. An IP address is a logical add
7 min read
IP address as logical address and MAC address as Physical address
Overview :IP addresses and MAC addresses are essential for data communication. Assume there are two networks. The first network has three devices: A, B, C and the second network has three devices: X, Y, Z. If a device A from the first network wishes to send data to a device Y in the second network, it must first determine where Y is located in the
6 min read
MAC Address and Random MAC Address
MAC Addresses are the address which are specified by the Manufacturer.MAC address help in communicating with the devices with communicating with other devices over the network. They are 12 digit hexadecimal numbers in which first three set bits specify the manufacturer of the device and last 3 specify the specific device. Random MAC Address They ar
3 min read
Why Do We Need IP Address if We Have Already MAC Address?
Answer: The network allots an IP address to every connected device making sure that every device can be identified separately within the network. Each device is identified by its MAC address, which cannot be shared by two devices. The MAC address is assigned by the embedded Network Interface Card (NIC) of each device and cannot be altered once set.
1 min read
Difference Between MAC Address and IP Address
Both MAC Address and IP Address are used to uniquely define a device on the internet. NIC Card’s Manufacturer provides the MAC Address, on the other hand, the Internet Service Provider provides the IP Address. In this article, we will learn about MAC Addresses, IP Addresses, and their differences. What is MAC Address?MAC, or Media Access Control is
6 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
Python script to get device vendor name from MAC Address
Prerequisite: Python Requests A MAC address is a unique identity of a network interface that is used to address the device in a Computer Network. What does MAC Address consist of? A MAC address is made up of 12 hexadecimal digits, 6 octets separated by ':'. There are 6 octets in a MAC address. In the first half, the manufacturer info is stored. How
2 min read
How To Modify MAC address in Windows 10 (Both Wired and Wireless Adapter)?
Prerequisite - Introduction of MAC Address, and Difference between MAC Address and IP Address A Media Access Control address is unique in nature which is doled out to a Network Interface Card to be utilized as a network address in communications within a network. In the Open Systems Interconnection network model, these addresses are utilized under
5 min read
How does a switch learn PC MAC Address before the PING process?
The switch has some intelligence and its networking device operates in the Layer 2 Data link layer in the OSI model. Here, we will see how the switch learns the MAC address of an end device PC even before the PING process between Switch and PC. Let's take an example of 2 PC'S connected to Switch. Note: There are no assigned IP Addresses to PCs. The
3 min read
What is MAC Address Table ?
MAC stands for Media Access Control it is a physical address that uniquely identifies a device and hardware manufacturer on a network. Most commonly used in  (IEEE 802) networking technologies, like Ethernet, WiFi, and Bluetooth technology. A mac address is globally unique so suppose two devices are on the internet they can not have the same MAC ad
3 min read
When You Move the NIC Cards from One PC to Another PC, Does the MAC Address Gets Transferred As Well?
Answer: Yes, the MAC Address Moves with the NIC Card. The MAC address is permanently embedded in the NIC circuitry, not the PC.When another NIC card is installed, the PC may have a different MAC address. When a Network Interface Card is transferred or is moved to another PC, the Media Access Control address also travels. It cannot use it; instead,
1 min read
What is MAC Address?
To communicate or transfer data from one computer to another, we need an address. In computer networks, various types of addresses are introduced; each works at a different layer. A MAC address, which stands for Media Access Control Address, is a physical address that works at the Data Link Layer. In this article, we will discuss addressing a DLL,
13 min read
How to Find Your Mac Address?
A MAC (Media Access Control) address is a unique identifier assigned to the network interface of a gadget. Whether you're troubleshooting network issues, setting up a secure connection, or filtering devices, knowing how to find your MAC address is essential. This article clarifies how to find your MAC address on different gadgets, including Windows
5 min read
Extracting email addresses using regular expressions in Python
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression. Let take an example in which we have to find out only email from the given input by Regular Expression. Examples: In
3 min read
Python | Pandas Extracting rows using .loc[]
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas provide a unique method to retrieve rows from a Data frame. DataFrame.loc[] method is a method that takes only index labels and r
3 min read
Extracting Tweets containing a particular Hashtag using Python
Twitter is one of the most popular social media platforms. The Twitter API provides the tools you need to contribute to, engage with, and analyze the conversation happening on Twitter, which finds a lot of application in fields like Data Analytics and Artificial Intelligence. This article focuses on how to extract tweets having a particular Hashtag
4 min read
Extracting locations from text using Python
In this article, we are going to see how to extract location from text using Python. While working with texts, the requirement can be the detection of cities, regions, states, and countries and relationships between them in the received text. This can be very useful for geographical studies. In this article, we will use the locationtagger library.
3 min read
Extracting patches from large images using Python
In this article, we are going to look at how we can extract patches from large images in Python. We will be using the patchify library to extract patches from images. Patchy is a Python library that can split images into small overlap able patches by given patch cell size, and merge patches into the original images. We prefer to utilize small photo
2 min read
Extracting text from HTML file using Python
Extracting text from an HTML file is a common task in web scraping and data extraction. Python provides powerful libraries such as BeautifulSoup that make this task straightforward. In this article we will explore the process of extracting text from an HTML file using Python. Use the below command to install the BeautifulSoup library: pip install b
3 min read
Extracting rows using Pandas .iloc[] in Python
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages that makes importing and analyzing data much easier. here we are learning how to Extract rows using Pandas .iloc[] in Python. Pandas .iloc[] Syntax Syntax: pandas.DataFrame.iloc[] Paramete
7 min read
What is Physical Address and Logical Address in Networking?
A physical address is a unique identifier given to network interfaces for communication over a physical network segment. A logical address is a unique address assigned to each networked device to identify its location and enable routing. In this article, we will discuss Physical Address and Logical Address. What is a Physical Address?The physical a
5 min read
Difference Between Network Address Translation (NAT) and Port Address Translation (PAT)
In the world of networking, most of the uses of IP addresses are important due to the limited availability of IPv4 addresses which is a part of network address translation. Two technologies that have been developed to address this problem are Network Address Translation and Port Address Translation. These technologies not only help to keep IP addre
6 min read
Extracting an attribute value with beautifulsoup in Python
Prerequisite: Beautifulsoup Installation Attributes are provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. A tag may have any number of attributes. For example, the tag <b class="active"> has an attribute “cl
2 min read
NLP | Extracting Named Entities
Recognizing named entity is a specific kind of chunk extraction that uses entity tags along with chunk tags. Common entity tags include PERSON, LOCATION and ORGANIZATION. POS tagged sentences are parsed into chunk trees with normal chunking but the trees labels can be entity tags in place of chunk phrase tags. NLTK has already a pre-trained named e
2 min read
Extracting the real and imaginary parts of an NumPy array of complex numbers
Numpy library gives us functions such as real() and imag() to find real and imaginary parts of a complex number. real() : To find real part of the complex number imag() : To find imaginary part of the complex number Example 1 : # importing the module import numpy as np # creating a NumPy array complex_num = np.array([-1 + 9j, 2 - 77j, 31 - 25j, 40
2 min read
Extracting Code From GeeksForGeeks Article
Prerequisite: bs4requestsModules Neededrequests- Requests allows you to send HTTP/1.1 requests extremely easily. This module also doesn't come built-in with Python. To install simply type the given command in the terminal.pip install requestsbs4 :- Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does
2 min read
PySpark - Extracting single value from DataFrame
In this article, we are going to extract a single value from the pyspark dataframe columns. To do this we will use the first() and head() functions. Single value means only one value, we can extract this value based on the column name Syntax: dataframe.first()['column name']Dataframe.head()['Index'] Where, dataframe is the input dataframe and colum
2 min read
How to install Python and PyCharm on Mac
Installing PyCharm on macOS is a straightforward process. PyCharm is a popular Integrated Development Environment (IDE) for Python programming, and it offers both a free community edition and a more feature-rich professional edition. In this article, I will guide you through the steps to install PyCharm on your macOS. MacOS Installation on PyCharmS
2 min read
How to Install Requests in Python - For Windows, Linux, Mac
Requests is an elegant and simple HTTP library for Python, built for human beings. One of the most famous libraries for Python is used by developers al over the world. This article revolves around how one can install requests library of Python in Windows/ Linux/ macOS using pip. Install Requests Module in Python in Window For installing requests in
4 min read
How to check Python Version : Windows, Linux and Mac
Python is a versatile and widely used programming language, and it is used for various tasks, from scripting to web development. Python, like many software, has different versions, and it's important to know which version is installed on your system. This information is crucial because different Python versions may have variations in syntax or libr
6 min read
Article Tags :
Practice Tags :