Home >Backend Development >Python Tutorial >How to generate MAC address using Python
In Python, you can use uuid.getnode() to generate a MAC address, and format() and re() to set the output format of the MAC address. Let's take a closer look at Python's method of obtaining the MAC address. I hope it will be helpful to you.
What is a MAC address?
The MAC address, also called the hardware address, is always unique, so there are no two devices with the same MAC address on the local network.
The main purpose of a MAC address is to provide a unique hardware address or physical address to each node on a local area network (LAN) or other network. A node represents the point at which a computer or other device (such as a printer or router) will remain connected to the network.
Method to generate MAC address
Method 1. Use uuid.getnode()
With the help of the getnode() method of the uuid module, it can be used to obtain the MAC address of the computer.
import uuid print (hex(uuid.getnode()))
Rendering:
It can be seen that the output MAC address is not in a formatted form and has no separators.
Method 2, use getnode() format()
Based on method 1, use the format() method to get a better output format
import uuid print ("格式化的MAC地址为 : ", end="") print (':'.join(['{:02x}'.format((uuid.getnode() >> ele) & 0xff) for ele in range(0,8*6,8)][::-1]))
Rendering:
It can be seen that the formatted MAC address is output, but the code written in this way seems very complicated. In order to reduce the complexity property, we can add a re() method
Method 3. Use getnode() findall() re()
import re, uuid print ("格式化且不太复杂的MAC地址为 : ", end="") print (':'.join(re.findall('..', '%012x' % uuid.getnode())))
Output:
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
The above is the detailed content of How to generate MAC address using Python. For more information, please follow other related articles on the PHP Chinese website!