Home  >  Article  >  Backend Development  >  How to generate MAC address using Python

How to generate MAC address using Python

青灯夜游
青灯夜游Original
2018-12-22 14:30:025415browse

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.

How to generate MAC address using Python

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:

How to generate MAC address using Python

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:

How to generate MAC address using Python

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:

How to generate MAC address using Python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn