例如,我有一个值为“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/