I have the following MicroPython code running on an ESP32:
import network
wlan_sta = network.WLAN(network.STA_IF)
wlan_sta.active(True)
wlan_mac = wlan_sta.config('mac')
print("MAC Address:", wlan_mac) # Show MAC for peering
The output looks like this:
MAC Address: b'0\xae\xa4z\xa7$'
I would like to display it in the more familiar format of six pairs of hex digits, like this:
MAC Address: AABBCC112233
After searching for a solution on the internet, I've tried:
print("MAC Address:", str(wlan_mac))
but it displays the same as when not using str()
print("MAC Address:", hex(wlan_mac))
but it results in TypeError: can't convert bytes to int
print("MAC Address:", wlan_mac.hex())
but it says AttributeError: 'bytes' object has no attribute 'hex'
I am also a little suspicious of the bytes retrieved from wlan_sta.config('mac')
. I would have expected something that looked more like b'\xaa\xbb\xcc\x11\x22\x33'
instead of b'0\xae\xa4z\xa7$'
. The z and the $ seem very out of place for something that should be hexadecimal and it seems too short for what should be six pairs of digits.
So my question is two-fold:
I am also a little suspicious of the bytes retrieved from wlan_sta.config('mac'). I would have expected something that looked more like b'\xaa\xbb\xcc\x11\x22\x33' instead of b'0\xae\xa4z\xa7$'. The z and the $ seem very out of place for something that should be hexadecimal and it seems too short for what should be six pairs of digits.
You're not getting back a hexadecimal string, you're getting a byte string. So if the MAC address contains the value 7A
, then the byte string will contain z
(which has ASCII value 122 (hex 7A
)).
Am I using the correct method to get the MAC address?
You are!
If it is correct, how can I format it as six pairs of hex digits?
If you want to print the MAC address as a hex string, you can use the
ubinascii.hexlify
method:
>>> import ubinascii
>>> import network
>>> wlan_sta = network.WLAN(network.STA_IF)
>>> wlan_sta.active(True)
>>> wlan_mac = wlan_sta.config('mac')
>>> print(ubinascii.hexlify(wlan_mac).decode())
30aea47aa724
Or maybe:
>>> print(ubinascii.hexlify(wlan_mac).decode().upper())
30AEA47AA724