Search code examples
c++arduinoesp8266esp32

Convert String in to MAC address


Inside the file in SPIFFS, I'm saving information about the mac address in the form "XX:XX:XX:XX:XX:XX". When I read the file, I need to switch it from STRING to a array of hexadecimal values.

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()));

But I'm wrong in the code somewhere

When i put AA:00:00:00:00:01 in file, my ESP8266 set 29:D5:23:40:00:00

I need help, thank you


Solution

  • You are returning a pointer to a "local" variable, i.e. one which's lifetime ends when the function is finished. Using such a pointer then is UB, which may be, for example, the behaviour you are seeing.

    To overcome this, you could pass the array as parameter; then the caller is responsible for memory management. BTW: you could use format %hhx to read in directly into an 8 bit unsigned data type:

    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]);
            }
        }
    }