参宿四的小木屋

参宿四的小木屋

【Bin】如何修改ESP32的MAC地址

2025-08-30
【Bin】如何修改ESP32的MAC地址

在部分情况下,我们可能需要修改ESP32的MAC地址为自定义MAC以符合网络管理要求。

查阅 乐鑫官方文档关于MAC地址 可知在 ESP-IDF 中,各个网络接口的 MAC 地址是根据单个 基准 MAC 地址 (Base MAC address) 计算出来的。默认情况下使用乐鑫指定的基准 MAC 地址,该基准地址在产品生产过程中已预烧录至 ESP32 eFuse。

默认的基准 MAC 地址在出厂时已预烧录至 eFuse BLK0 中,如需设置自定义基准 MAC 地址,需要在初始化任一网络接口或调用 esp_read_mac() 函数前调用 esp_base_mac_addr_set() 函数。

该函数构成为esp_base_mac_addr_set(const uint8_t *mac) 具体函数信息可参见此处

接下来我们使用此函数写一个示例程序进行测试,示例源码

#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <esp_wifi.h>



IPAddress local_IP(192,168,1,1);  //  主机地址
IPAddress gateway(192,168,1,1);   //  网关地址
IPAddress subnet(255,255,255,0);  //  子网掩码

const char *ssid = "yourAP";  //  WIFI名称
const char *password = "yourPassword";  //  WIFI密码
const int  channel = 1; //  WIFI信道(1~13)
const int  ssid_hidden = 0;  //  是否隐藏WIFI(0为不隐藏,1为隐藏)
const int  max_connection = 4; //  最大连接数(1~4)

uint8_t newMACAddress[] = {0x32, 0xAE, 0xA4, 0x07, 0x0D, 0x66}; //您需要设置的MAC地址




void setup() {
  Serial.begin(115200); //  初始化串口
  Serial.println();
  Serial.println("程序运行");
  esp_base_mac_addr_set(&newMACAddress[0]); //  在启动AP前将自定义地址装载,此方法需要在调用esp_read_mac()前使用,否则无效! 
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(local_IP, gateway, subnet); //设置AP地址
  if (!WiFi.softAP(ssid, password,channel,ssid_hidden,max_connection)) {
    log_e("AP创建失败!");
    while(1);
  }
  Serial.print("[OLD] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());
  
  Serial.print("[NEW] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());

}

void loop() {
  // put your main code here, to run repeatedly:

}

由于esp_base_mac_addr_set() 需要在调用前使用,故此处OLD和NEW项MAC地址为同一地址

如果需要在网络初始化后设置网络接口使用的特定 MAC,可以使用esp_netif_set_mac() 函数完成设置

注意:使用esp_netif_set_mac() 可能会造成基准MAC短暂出现在网络中