c++ - MAC地址:pad missing left Zeros

标签 c++

例如,我有一个值为“0:22:3f:a:5d:16”的 MAC 地址,如何将其转换为人类可读的格式,如“00:22:3f:0a:5d:16” ?
我的 mac 地址缺少前导零,因为我使用

string asd = ether_ntoa ((struct ether_addr *)p->add2);//p->add2 is a unsigned char[6]

ether_nota 删除了前导零,我不知道是否有其他方法可以将正确的 MAC 地址存储为字符串。

最佳答案

implementation导致它在没有零填充的情况下打印只是一个 printf他们在哪里使用%x而不是 %02x . struct ether_addr格式为 documented in the man page ,因此它的内部不是私有(private)的。

The structure ether_addr is defined in <net/ethernet.h> as:

struct ether_addr {
    uint8_t ether_addr_octet[6];
}

话虽如此,我会实现我自己的版本。 rz在这里表示可重入和零填充。
char *ether_ntoa_rz(const struct ether_addr *addr, char *buf)
{
    sprintf(buf, "%02x:%02x:%02x:%02x:%02x:%02x",
            addr->ether_addr_octet[0], addr->ether_addr_octet[1],
            addr->ether_addr_octet[2], addr->ether_addr_octet[3],
            addr->ether_addr_octet[4], addr->ether_addr_octet[5]);
    return buf;
}

不可重入版本只有一个静态缓冲区并调用可重入缓冲区。
char *ether_ntoa_z(const struct ether_addr *addr)
{
    static char buf[18];    /* 12 digits + 5 colons + null terminator */
    return ether_ntoa_rz(addr, buf);
}

如果想看glibc中函数的实现,可以find it if you search .

关于c++ - MAC地址:pad missing left Zeros,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4736718/

相关文章:

c++ - 使用模板化类指定给 RtlValidateHeap 错误的无效地址

c++ - Imshow() 大小限制

c++ - 使用 masm 编译程序集文件时表达式中缺少运算符

c++ - 递归可迭代模板函数 C++

c++ - gcc 发出的这个越界警告是错误的吗?

c++ - 将声明为 `extern char[]` 的变量传递给 VC++ 中的函数模板时出错

c++ - 混淆在C++中实现rehash()函数

c++ - 删除已声明为新的指针时出错?

c++ - 为什么不定义 `__cxa_throw` 会导致链接错误?

c++ - 哈希函数和哈希表中的存储