gpt4 book ai didi

c - 打印 MAC 地址时出现问题

转载 作者:行者123 更新时间:2023-11-30 16:56:48 27 4
gpt4 key购买 nike

MAC 地址被解析为字节数组 (macaddr)。字节是用 printf() 依次打印。这些字节应该看起来像十六进制字符对。但其中一些是用 f 填充的字符。

例如,对于macaddr[3],它打印'ffffffcc'而不是'cc',即4 个字节而不是单个字节。打印其余的数组项正确(macaddr[0] = 00macaddr[1] = AAmacaddr[2 ] = BB,等)

有什么问题吗?请帮我找出程序出了什么问题。

#include <stdio.h>
#include <net/if.h> // struct ifconf
#include <errno.h>
#include <libnet.h>
#include <pcap.h>
#include <stdlib.h>
#include <unistd.h>

int getmacaddr() ;

int main(int argc, char *argv[])
{
getmacaddr();
}

int getmacaddr()
{
struct ifconf ifc;
struct ifreq *ifr;
int sfd;
int i;
int devnums;
char macaddr[ETHER_ADDR_LEN];

ifc.ifc_req = NULL;

sfd = socket(AF_INET,SOCK_DGRAM,0);
if(sfd == -1)
{
perror("socket : ");
return -1;
}

// get ifc.ifc_len
if(ioctl(sfd,SIOCGIFCONF,&ifc) == -1)
{
perror("ioctl - SIOCGIFCONF : ");
return -1;
}
devnums = ifc.ifc_len / sizeof(struct ifreq);

// malloc ifc.ifc_buf and get IFCONF list
ifc.ifc_buf = malloc(ifc.ifc_len);
memset(ifc.ifc_buf,0x0,ifc.ifc_len);

if(ioctl(sfd,SIOCGIFCONF,&ifc) == -1)
{
perror("ioctl - SIOCGIFCONF : ");
return -1;
}


for(i = 0; i < devnums; i++,ifc.ifc_req++)
{
// idfy dev
if( strcmp(ifc.ifc_req->ifr_ifrn.ifrn_name,"lo") && ifc.ifc_req->ifr_ifrn.ifrn_name != 0)
{
ifr = ifc.ifc_req;

// IP address
struct sockaddr_in *a = (struct sockaddr_in *) &ifr->ifr_addr;
printf("%s",inet_ntoa(a->sin_addr));
printf("\n");

//get IFHWADDR
if(ioctl(sfd,SIOCGIFHWADDR,ifr) == -1)
{
perror("ioctl - SIOCGIFHWADDR : ");
return -1;
}
}
}

memcpy(macaddr,ifr->ifr_hwaddr.sa_data,sizeof(macaddr));
for(i = 0; i < ETHER_ADDR_LEN; i++)
{
printf("%02x ",macaddr[i]);
}
printf("\n");

close(sfd);
// free(ifc.ifc_buf); <- ?? error

return 0;
}

编辑

我替换了以下行:

printf("%02x ",macaddr[i]);

printf("%02x ", (macaddr[i] & 0xff));

最佳答案

试试这个:

printf("%02x ", (unsigned char)macaddr[i] & 0xff);

我们在格式字符串中指定最小字段宽度。因此,为了确保该值看起来与单个字节完全相同,您可以通过应用位掩码仅保留前 16 位。

关于c - 打印 MAC 地址时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com