0

I have a function that converts a mac address from the forma00:11:22:33:44:55 to a 6 Byte array using strtol(). Now my function basically works fine but I'm wondering how I do proper error checking past the first conversion. thus far, my code looks like this:

char* pEnd = NULL;
errno = 0;
// wanmac shall be formatted like: "00:11:22:33:44:55"
// Check for valid index into switch_wan_macs array
if (idx<0 || idx> MAX_WAN_PORTS){
    return BCM_E_FAIL;
}
// set wan_mac
//interpret the 6 bytes of the mac with base 16 (hex) while omitting the colons (move next pointer up by 1)
switch_wan_macs[idx].wan_mac[0] = strtol (wan_mac, &pEnd, 16);
if (pEnd == wan_man || errno == ERANGE) {
    printf("Conversion of MAC string %s failed\n", wan_mac);
    return BCM_E_FAIL;
}
switch_wan_macs[idx].wan_mac[1] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[2] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[3] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[4] = strtol (pEnd+1, &pEnd, 16);
switch_wan_macs[idx].wan_mac[5] = strtol (pEnd+1, NULL, 16);

return BCM_E_NONE;

and I can really convert the remaining string to the original string in any subsequent steps. Should I best use a temporary array a la char pEnd[6]?

stdcerr
  • 13,725
  • 25
  • 71
  • 128

1 Answers1

1

Why not use sscanf?

#include <stdio.h>

int main() {
  char mac[20] = "00:11:22:33:44:55";
  unsigned a[6];

  if (6 != sscanf(mac, "%2x:%2x:%2x:%2x:%2x:%2x",
                  a, a+1, a+2, a+3, a+4, a+5)) {
    fprintf(stderr, "Error in mac string\n");
    return 1;
  }

  printf("%.2x %.2x %.2x %.2x %.2x %.2x\n",
      a[0], a[1], a[2], a[3], a[4], a[5]);

  return 0;
}

BTW, it looks like your valid idx check should possibly be idx>=MAX_WAN_PORTS (if you defined switch_wan_macs to have size MAX_WAN_PORTS).

ooga
  • 15,423
  • 2
  • 20
  • 21