首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析mac地址和移动临时时检查strtol()时出错。指针向上

解析mac地址和移动临时时检查strtol()时出错。指针向上
EN

Stack Overflow用户
提问于 2014-07-12 02:07:39
回答 1查看 285关注 0票数 0

我有一个使用strtol()将mac地址从00:11:22:33:44:55格式转换为6字节数组的函数。现在,我的函数基本上工作得很好,但我想知道如何在第一次转换后进行正确的错误检查。到目前为止,我的代码如下所示:

代码语言:javascript
复制
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]一样使用临时数组吗?

EN

回答 1

Stack Overflow用户

发布于 2014-07-12 02:33:42

为什么不使用sscanf

代码语言:javascript
复制
#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检查可能应该是idx>=MAX_WAN_PORTS (如果您定义switch_wan_macs的大小为MAX_WAN_PORTS)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24703875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档