将字符串转换为 MAC 地址

Convert String in to MAC address

在 SPIFFS 的文件中,我以 "XX:XX:XX:XX:XX:XX" 的形式保存有关 mac 地址的信息。 当我读取文件时,我需要将其从 STRING 切换为十六进制值数组。

uint8_t* str2mac(char* mac){
  uint8_t bytes[6];
  int values[6];
  int i;
  if( 6 == sscanf( mac, "%x:%x:%x:%x:%x:%x%*c",&values[0], &values[1], &values[2],&values[3], &values[4], &values[5] ) ){
      /* convert to uint8_t */
      for( i = 0; i < 6; ++i )bytes[i] = (uint8_t) values[i];
  }else{
      /* invalid mac */
  } 
  return bytes;
}

wifi_set_macaddr(STATION_IF, str2mac((char*)readFileSPIFFS("/mac.txt").c_str()));

但我的代码某处有误

当我将 AA:00:00:00:00:01 放入文件时,我的 ESP8266 设置 29:D5:23:40:00:00

我需要帮助,谢谢

您正在返回一个指向 "local" 变量的指针,即当函数完成时生命周期结束的指针。使用这样的指针那么就是UB,这可能是例如你看到的行为。

为了克服这个问题,您可以将数组作为参数传递;然后调用者负责内存管理。 顺便说一句:您可以使用格式 %hhx 直接读入 8 位无符号数据类型:

int str2mac(const char* mac, uint8_t* values){
    if( 6 == sscanf( mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",&values[0], &values[1], &values[2],&values[3], &values[4], &values[5] ) ){
        return 1;
    }else{
        return 0;
    }
}

int main() {

    uint8_t values[6] = { 0 };
    int success = str2mac("AA:00:00:00:00:01", values);
    if (success) {
        for (int i=0; i<6; i++) {
            printf("%02X:",values[i]);
        }
    }
}

您的代码似乎与 wifi_set_macaddr 不兼容(我查阅了 API 文档)。它需要一个指向 mac 地址的 uint8 指针,这意味着您编写它的方式将不起作用(返回指向局部变量等的指针)。这是一个您应该能够适应您的目的的示例:

#include <iostream>
#include <fstream>

// mock up/print result
bool wifi_set_macaddr(uint8_t index, uint8_t *mac) 
{
    std::cout << "index: " << (int)index << " mac: "; 
    for (int i = 0; i < 6; ++i)
        std::cout << std::hex << (int)mac[i] << " ";
    std::cout << std::endl;

    return true;
}


// test file
void writeTestFile()
{   
    std::ofstream ofs("mac.txt");
    if (!(ofs << "AA:00:00:00:00:01" << std::endl))
    {
        std::cout << "File error" << std::endl;
    }
    ofs.close();
}

int main() 
{
    writeTestFile();

    uint8_t mac[6];
    int i = 0, x;

    std::ifstream ifs("mac.txt");
    for (; i < 6 && ifs >> std::hex >> x; ++i)
    {
        mac[i] = static_cast<uint8_t>(x);
        ifs.ignore();
    }

    if (i < 6)
    {
        std::cout << "File error or invalid MAC address" << std::endl;
        return 1;
    }

    wifi_set_macaddr(0x00, mac);

    return 0;
}

http://coliru.stacked-crooked.com/view?id=d387c628e590a467