0

を使用して、MAC アドレスを形式00:11:22:33:44:55から 6 バイト配列に変換する関数がありますstrtol()。現在、私の関数は基本的に正常に動作していますが、最初の変換を過ぎて適切なエラーチェックを行う方法を知りたいです。これまでのところ、私のコードは次のようになります。

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;

その後の手順で、残りの文字列を元の文字列に実際に変換できます。一時的な配列を使用するのが最善char pEnd[6]ですか?

4

1 に答える 1

1

なぜ使用しないの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;
}

idxところで、あなたの有効なチェックはおそらくそうであるように見えます( size を持つidx>=MAX_WAN_PORTSように定義した場合)。switch_wan_macsMAX_WAN_PORTS

于 2014-07-11T18:33:41.660 に答える