例如,我有一个值为"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地址存储为字符串。
发布于 2011-01-20 02:06:31
导致它打印时没有填充的implementation只是一个printf,他们使用%x而不是%02x。struct ether_addr格式是documented in the man page,因此它的内部结构不是私有的。
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。
https://stackoverflow.com/questions/4736718
复制相似问题