我有这个代码。屏幕显示变量值的两倍并且是不同的。为什么?难道我做错了什么? Linux用gcc编译。 我不明白这个错误。该值不应在函数中更改。
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
int main()
{
int fd;
struct ifreq ifr;
char *iface = "eth0";
unsigned char *mac, *ip, *mask, *broad;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
//get the ip address
ioctl(fd, SIOCGIFADDR, &ifr);
ip= (unsigned char *)inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr )->sin_addr);
//display ip
printf("IP address of %s - %s\n" , iface , ip );
//get the netmask ip
ioctl(fd, SIOCGIFNETMASK, &ifr);
mask = (unsigned char *)inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr )->sin_addr);
//display netmask
printf("Netmask of %s - %s\n" , iface , mask);
//get the MAC address
ioctl(fd, SIOCGIFHWADDR, &ifr);
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
//display mac address
printf("Mac of %s - %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" , iface, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
//get the BroadCast ip
ioctl(fd, SIOCGIFBRDADDR, &ifr);
broad = (unsigned char *)inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr )->sin_addr);
//display BroadCast
printf("Broadcast of %s - %s\n" , iface , broad);
close(fd);
//display ip
printf("IP address of %s - %s\n" , iface , ip );
//display netmask
printf("Netmask of %s - %s\n" , iface , mask);
//display mac address
printf("Mac of %s - %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" ,iface, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
//display BroadCast
printf("Broadcast of %s - %s\n" , iface , broad);
return 0;
}
答案 0 :(得分:2)
每次调用ioctl
都会覆盖ifr
中的内容。
ip
只是指向ifr
结构的指针。当您打印ip
时,会打印从上次调用ioctl
获得的地址。
您可以通过在调用中使用不同的struct ifreq
或将要保留的数据复制到另一个内存区域(例如使用strdup
)来解决问题。