esp8266 mac адрес узнать

Get ESP32/ESP8266 MAC Address and Change It (Arduino IDE)

This guide shows how to get the ESP32 or ESP8266 boards MAC Address using Arduino IDE. We also show how to change your board’s MAC Address.

What’s a MAC Address?

MAC Address stands for Media Access Control Address and it is a hardware unique identifier that identifies each device on a network.

MAC Addresses are assigned by manufacturers, but you can also give a custom MAC Address to your board. However, every time the board resets, it will return to its original MAC Address. So, you need to include the code to set a custom MAC Address in every sketch.

Get ESP32 or ESP8266 MAC Address

To get your board MAC Address, simply upload the following code to the ESP32 or ESP8266. The code is compatible with both boards.

Demonstration

After uploading the code, open the Serial Monitor at a baud rate of 115200. Press the on-board RESET or EN button.

The MAC Address should be printed in the Serial Monitor as shown in the following figure.

That’s it! Now, you know how to get your ESP32 or ESP8266 board MAC Address.

Set a Custom MAC Address for ESP32 and ESP8266

In some applications, it might be useful to give your boards a custom MAC Address. However, as explained previously, this doesn’t overwrite the MAC Address set by the manufacturer. So, every time you reset the board, or upload a new code, it will get back to its default MAC Address.

Change ESP32 MAC Address (Arduino IDE)

The following code sets a custom MAC Address for the ESP32 board.

You can set a custom MAC Address in the following line:

After uploading the code, open the Serial Monitor at a baud rate of 115200. Restart the ESP32 and you should get its old and new MAC Address.

Change ESP8266 MAC Address (Arduino IDE)

The following code sets a custom MAC Address for the ESP8266 board.

Set your custom MAC Address on the following line:

After uploading the code, open the Serial Monitor at a baud rate of 115200. Restart the ESP8266 and you should get its old and new MAC Address.

Wrapping Up

In this quick guide, we’ve shown you how to get your ESP32 and ESP8266 manufacturer MAC Address with Arduino IDE. You’ve also learned how to set a custom MAC Address for your boards.

Learn more about the ESP32 and ESP8266 boards:

Thanks for reading.

[eBook] Build Web Servers with ESP32 and ESP8266 (2nd Edition)

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…

ESP32 MQTT – Publish DHT11/DHT22 Temperature and Humidity Readings (Arduino IDE)

Installing ESP8266 NodeMCU Board in Arduino IDE 2.0 (Windows, Mac OS X, Linux)

Flashing NodeMCU Firmware on the ESP8266 using Windows

Enjoyed this project? Stay updated by subscribing our newsletter!

12 thoughts on “Get ESP32/ESP8266 MAC Address and Change It (Arduino IDE)”

Hi Ion.
That’s great!
I’m glad you’ve found this tutorial useful 😀
Regards,
Sara

Hello,
i am building a “digital twin” of an LEGO technic Hub, by using an ESP32.
Target is that ESP32 can be connected to LEGO BLE Apps.

Question is, how to change Advertising address is scetch to be shown as “LegoSyste” like : 90:84:2b:aa:bb:cc for example

Источник

ESP8266: Get MAC address

The objective of this short post is to explain how to get the MAC address of the ESP8266.


Introduction

The objective of this short post is to explain how to get the MAC address of the ESP8266.

Explaining in detail what is a MAC address is outside of the scope of this post. But, just as a quick explanation, the MAC address is a unique value associated with a network adapter [1]. So, MAC addresses are hardware addresses that uniquely identify a network adapter [1].

Taking in consideration the OSI model, MAC addressing works at a layer (layer 2) lower than IP addressing (layer 3) [1].

In terms of format, MAC addresses are 48-bit in length [2] and typically represented in hexadecimal format, with each two hexadecimal digits separated by “:”.

The first 24 bits of the MAC are the identifier number of the manufacturer and the second 24 bits are a serial number assigned by the manufacturer [2].

You can read more about MAC addresses here.

The tests were performed using a NodeMCU board, a very cheap and easy to use ESP8266 board. The board can be bought at eBay here.


The code

The code for this tutorial is very simple, since we already have a function to get the MAC of the ESP8266.

Читайте также:  ланолин что это такое

Since we only want to print the MAC, we will do all the coding on the setup function and leave the main loop empty.

First, we include the ESP8266WiFi library, which we typically use to access all the functionality needed for the ESP8266 to connect to a WiFi network. Then, in our setup function, we open the serial port, so we can print the output of our program.

To get the MAC dress of the ESP8266, we simply call the macAdress method on the WiFi global variable, which will return the MAC address in the hexadecimal format mentioned early.

You can check the full working code bellow, which also includes the empty loop function.


Testing the code

To test the code, just upload it to the ESP8266 and open the Arduino IDE console. You should get something similar to figure 1.

Figure 1 – Output of the function to get the MAC of the ESP8266.

Just to confirm what was explained in the introduction section, we can check if the first 24 bits of the MAC correspond to the manufacturer of the ESP8266, which is Espressif. You can check yours here. It should indicate Espressif, as shown i figure 2.

Figure 2 – Result of vendor lookup from the ESP8266 MAC.

Источник

Статья Определяем кто дома с помощью ESP8266

Приветствую всех читателей Codeby!
Сегодня мы создадим устройство, которое будет обнаруживать устройства вокруг. Сделаем простой проект, который будет обнаруживать, кто из родственников находиться дома, для примера.

Например, когда кто-то из семьи возвращается домой, передача пакетов с его телефона будет обнаружена и заставит, например, синий светодиод включится.
Мы будем обнаруживать более одного устройства одновременно.

Смартфоны и другие устройства с поддержкой Wi-Fi отправляют радиосигналы, называемые зондирующими(пробными) кадрами(Probe Frame), для обнаружения близлежащих беспроводных сетей, что позволяет легко отслеживать их, прослушивая их уникальный MAC-адрес.
На эту тему было мною было написано несколько статей
— Пассивная слежка через WIFI с помощью Probequest
— Детектор деаутентификации (диссоциации) клиентов. Часть 2

Чтобы показать, как работает этот вид отслеживания, мы можем запрограммировать NodeMCU Arduino на прослушивание пакетов любого устройства, которое мы хотим отслеживать, включая светодиод, когда он обнаруживается поблизости.
Широкое отслеживание представляет собой серьезную проблему конфиденциальности, побуждая большинство производителей применять такие меры безопасности, как рандомизация MAC-адресов, которая защищает от произвольного мониторинга MAC-адресов.

Проблема рандомизиции MAC-адресов.

Рандомизация MAC-адресов полезна для предотвращения некоторых типов отслеживания, но в тестах на различных телефонах Android было выясненно, что рандомизация MAC-адресов далека от совершенства. Существует несколько условий, при которых телефон возвращается к своему реальному MAC-адресу.
После обнаружения знакомой сети, сохраненной в списке предпочтительных сетей, устройство попытается подключиться к сети и может стать доступным для отслеживания.

Помимо просмотра сети Wi-Fi в списке предпочтительных сетей, активное подключение к сети устройство также будет активно показывать(палить) свой постоянный MAC-адрес. Это означает, что если вы захотите отследить кого-то, приходящего домой или проходящего мимо кафе с общим именем сети, рандомизация MAC-адресов не помешает вам это сделать.

К сожалению, большинство Android устройств генерируют пакеты тестовых кадров, используя реальный MAC-адрес, каждый раз, когда вы включаете Wi-Fi или открываете меню выбора сети Wi-Fi.

Чтобы сделать этот проект более наглядным и обеспечить легкий способ обнаружения, когда ваше устройство передает свой реальный MAC-адрес, я решил изменить код, включив в него несколько светодиодов и возможность отслеживать столько MAC-адресов, сколько имеется доступных контактов для управления светодиодами.
В нашем случае будем отслеживать 4 устройства.

Есть некоторые проблемы, которые нам нужно преодолеть при использовании светодиода, например, тот факт, что использование задержки для удержания светодиода в течение достаточно долгого времени, чтобы его можно было заметить, что таймер приводил к сбою в работе светодиодов(далее будет объяснена проблема).

Чтобы решить эту проблему, я добавил таймер, который включал бы светодиод при обнаружении пакета с совпадающим MAC-адресом и оставлял его включенным до тех пор, пока не будет обнаружено установленное количество пакетов, которые не соответствуют искомому MAC-адресу; Это позволяет нам легко изменять продолжительность работы светодиода.

Шаг 1. Поиск MAC-адреса устройства.
Сперва стоит определить какие устройства мы будем обнаруживать, для этого получим их MAC-адреса.
Лучший способ это подключиться к сети, в которой есть устройство, которое вы хотите отслеживать, и затем запустить сканирование сети с помощью Fing или Nmap.
Я лично поступил по старинке и заглянул в аренду DCHP адресов в настройках роутера.

Шаг 5. Смотрим код.
Чтобы понять, что делает этот код, давайте заглянем внутрь.
Первый раздел кода устанавливает переменные. Здесь мы определяем размер списка MAC-адресов, которые мы отслеживаем, фактические MAC-адреса в списке и имена целей, связанных с MAC-адресами в списке.

Затем у нас есть раздел настроек, в котором мы устанавливаем выводы D5, D6, D7 и D8 для вывода, чтобы мы могли использовать их для управления светодиодами.

Поэтому на данном этапе были добавлены свои таймеры для каждого устройства.

Здесь у нас имеется обычный цикл, который пытается сопоставить адреса отправителя и получателя в обнаруженном пакете с MAC-адресами в нашем списке(которые мы отслеживаем).

Читайте также:  ветклиники в тосно адреса

Вот фрагмент кода, который управляет тем, что происходит, когда мы обнаруживаем искомый MAC-адрес. Во-первых, мы видим, что мы печатаем имя устройства в последовательный порт, который вы открыть, щелкнув меню «Инструменты» в Arduino IDE, а затем выбрав опцию «Монитор последовательного порта».

Чтобы контролировать цвет светодиода, я использовал оператор «if», который говорит, что если мы обнаружили пакет с MAC-адресом, совпадающим с нашим в нашем списке, подсвечиваем цвет в соответствующий цвет.

Поскольку большинство списков в программировании начинаются с 0, примером может быть то, что первым MAC-адресом в списке будет индекс 0 и установлен синий цвет. Второй MAC-адрес будет индексом 1 и установлен в красный цвет. И третий будет индекс 2 и будет установлен в зеленый цвет.

Последняя часть кода управляет переключением каналов, и мы не будем ее рассматривать.

Окончательный код должен выглядеть следующим образом:

После этого мы можем скомпилировать проект нажав на галочку и замет залить наш скетч в плату NodeMCU.

Шаг 7. Сборка.
В этом коде я сохранил простоту компоновки, используя выводы D5, D6, D7 и D8 для управления светодиодами.
Если вы хотите сохранить свои светодиоды, я рекомендую вместо этого подключить выводы D5, D6, D7 и D8 к светодиоду в другом месте на плате, а затем добавить резистор (или потенциометр), чтобы уменьшить напряжение и продлить срок службы светодиодов.

После этого можно подключить USB-кабель и проверить работоспособность. Как только устройства из списка отслеживаемых отправит пакет, соответствующий светодиод загорится. Я лично долго тестировал и работало все на отлично.

Источник

Get module’s MAC address? #313

Comments

stozk commented May 23, 2015

with the nodeMCU firmware I can read the modules preset MAC address.
Is this also possible with the esp8266 arduino sdk FW?

There are functions like «ESP.getChipId()» which return the chip’s ID, but WiFi.macAddress(mac) can only be used to set an hard coded address, but I just want to read the modules original MAC.

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

BJvDL commented May 23, 2015

I borrowed this from an example, it works

String clientMac = «»;
unsigned char mac[6];
WiFi.macAddress(mac);
clientMac += macToStr(mac);

String macToStr(const uint8_t* mac)
<
String result;
for (int i = 0; i

stozk commented May 23, 2015

Ah nice thanks, thank you very much.
So if I pass an empty char array it will return the preset MAC?

BJvDL commented May 23, 2015

Yes. I use it for the ClientID with the MQTT connection

stozk commented May 23, 2015

I have simplified it a bit (imo ;-))

String getMacAddress() <
byte mac[6];
WiFi.macAddress(mac);
String cMac = «»;
for (int i = 0; i

lvalero commented Mar 29, 2016

Leadnig «0» are missing, fixed here, thank you :

String macToStr(const uint8_t* mac)
<
String result;
String atom;
for (int i = 0; i

Humancell commented Mar 29, 2016

String getMacAddress() <
byte mac[6];

WiFi.macAddress(mac);
String cMac = «»;
for (int i = 0; i

mtnbrit commented Mar 29, 2016

igrr commented Apr 1, 2016

Or simply String s = WiFi.macAddress();

lvalero commented Apr 2, 2016

i assume the function macToStr () is still needed when you scan the network WiFi.scanNetworks(); in order to retrieve BSSIDs

igrr commented Apr 2, 2016

lvalero commented Apr 2, 2016

indeed., thank you igrr

shaneaj commented Jan 4, 2017 •

This code has help me with my temperature sensor and MQTT project. However when I print out the mac address it displays in the reserve order.

MAC: 60:01:94:0E:A1:D6 (this is what i want to see)
MAC: D6:A1:0E:94:01:60 (this is how it displays)

fxoislac commented Mar 20, 2017

I came on this thread because it seems that WiFi.macAddress() returns a reversed mac address (I think I have the same problem you have), so I had to reverse it in order to get the correct mac address to set in the «wifi protection by mac address» option on my router.

So basically, if you take the provided example by Arduino: [https://www.arduino.cc/en/Reference/WiFiMACAddress]

You can do something like that from Humancell topic above:

`
String getMacAddress() <
byte mac[6];
byte mac_reversed[6];
WiFi.macAddress(mac);

mostafaragab1 commented Jan 26, 2019

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Set MAC address? #413

Comments

vshymanskyy commented Jun 11, 2015

I know how to get the MAC address:

Is there any way to set it?
In the AT firmware, there are commands for this, so I think it should be possible:

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

Читайте также:  картины для кухни на стену фото в интерьере

chadouming commented Jun 21, 2015

This is not an issue, ask your question in relevant part of the forum : Forum

vshymanskyy commented Jun 21, 2015

Actually it was meant as a feature request, as I didn’t find anything like that (I looked into the code).
Sorry if I missed something.

igrr commented Jun 21, 2015

This isn’t implemented currently, but SDK has the wifi_set_macaddr function to set MAC addresses. There is a limitation though — this function has to be called early at startup, before setup() method is run. So it’s not clear how to make this feature available through Arduino APIs. AT firmware saves the new MAC to EEPROM and restarts, if I remember correctly.

vshymanskyy commented Jun 21, 2015

Thanks for a quick reply! Could we do it the same way, so for example it would change the MAC in the EEPROM, to be applied after restart (no need to restart immediately)?

sunnyhighway commented Jul 24, 2015

I don’t think wifi_set_macaddr would cause a reboot, because (according to the SDK programming guide) it returns true or false depending on succes or failure to do so.

It would be pointless to return anything at all if it would cause a reboot, would it?

Links2004 commented Jul 25, 2015

with my change it shut work like this:

ikin77 commented Dec 16, 2015

Hi, does anybody knows why I do get this compiling error?

undefined reference to `wifi_set_macaddr(unsigned char, unsigned char*)’

byte mac[6];
. // Set mac value.
WiFi.macAddress(mac);
wifi_set_macaddr(STATION_IF, mac);
.

luc-github commented Dec 16, 2015

ikin77 commented Dec 16, 2015

@luc-github
Thanks. I just did «#include «

Now I can compile :o) Thanks again!!

ikin77 commented Dec 17, 2015

Hi. I can now change MAC address as STA and SOFAP. When I check on my router’s page, I can see the MAC address, buy I can see the different devices names as «ESP-XXXX»

Can it be changed? I do I do it? Thanks again!!

Links2004 commented Dec 17, 2015

vogtitec commented Dec 27, 2015

ikin77 commented Dec 27, 2015

Hi. Tomorrow morning I’ll post the sample code.

ikin77 commented Dec 28, 2015

In my sample code I read the original MAC and I change only some bytes. Yo can change others or all or them.

vogtitec commented Dec 28, 2015

ikin77 commented Dec 29, 2015

I couldn’t change the hostnamed, the suggested solution doesn’t seems to make any difference. Maybe were not using the function at the right moment, I don’t know :o/

Links2004 commented Dec 29, 2015

you need to call it before the DHCP request is made.
may direct after setup.

Duality4Y commented Dec 29, 2015

for setting a hostname you need to run a dhcp server somewhere in your network.
so that other devices can also find it.

Links2004 commented Dec 29, 2015

@Duality4Y I think you mean:
the DHCP server needs to «add» the names to the DNS server.
the DHCP server itself does not response to a DNS request 😉

Duality4Y commented Dec 29, 2015

yes sorry that is correct.

vshymanskyy commented Dec 26, 2016 •

It looks it got broken at some point.

yoursunny commented Jul 17, 2017

I’ve posted a complete example of changing MAC and hostname in my blog:
https://yoursunny.com/t/2017/change-ESP8266-MAC/

IMAN4K commented Jan 29, 2019 •

Worked in core 2.4.2 + ESP-12E

sepp89117 commented Jun 6, 2019 •

extern «C» void preinit() <
uint8_t ap_mac[] = <0xD8, 0x96, 0x85, 0x03, 0x04, 0x05>;
wifi_set_opmode(SOFTAP_MODE);
wifi_set_macaddr(SOFTAP_IF, ap_mac);
>

Worked for me in core 2.5.2 + ESP-12E for SoftAP
Thanks @IMAN4K

happytm commented Aug 31, 2019

Is it possible to dynamically change mac bytes in code by replacing byte with temperature,humidity and pressure sensor values read from BME280 that way Raspberry running monitor mode can capture these sensor values?

sepp89117 commented Aug 31, 2019

hi, why do you want to do that?
Please describe your project.

happytm commented Aug 31, 2019

sepp89117 commented Aug 31, 2019

In that case I would have used a 433Mhz interface. With a transmitter in the Arduino transfer the data and listen with the Pi simply.
But if you want to stay with your hardware setup, did you try the code above?
Try wifi_set_macaddr in your action. Theoretically, it should work.

happytm commented Aug 31, 2019

I want to go with only ESP device for hardware simplicity.Yes I will try wifi_set_macaddr.

happytm commented Sep 22, 2019

I was able to create ad-hoc network between 2 ESP8266 devices and I can exchange 6 bytes of data between 2 devices reliably in about 200 milliseconds. I am using:
int n = WiFi.scanNetworks(true, true, 7);
to scan all aps with channel 7 which shows up with 4 AP’s in my vicinity.

To reduce the time it takes to scan few AP’s (60 millisecponds) I want to scan only one known AP with known SSID.

Источник

Образовательный портал