c - 为什么它会改变变量的值?

标签 c linux

我有这个代码。屏幕显示变量值的两倍并且不同。为什么?难道我做错了什么? 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;
}

最佳答案

每次调用ioctl都会覆盖ifr中的内容。

ip 只是指向 ifr 结构的指针。当您打印ip时,您会打印从上次调用ioctl获得的地址。

您可以通过在调用中使用不同的 struct ifreq 或将要保留的数据复制到另一个内存区域(例如使用 strdup)来解决您的问题.

关于c - 为什么它会改变变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33999700/

相关文章:

c++ - 在 MPI_Init() 之前初始化变量,在 MPI_Finanlize() 之后初始化变量

c++ - Eclipse CDT : How to find all the places that a variable is modified

linux - 嵌入式linux如何通过usb gadget检测文件被修改&更新文件

c - 将指针数组传递给函数

c - 加勒比在线法官期间运行时错误

python - 在 Linux 程序中嵌入 Python

java - 在 Linux (Ubuntu 3.0.0) 上的 Eclipse 中设置 OpenGL ES 1.0 以进行 Android 开发

c - Linux - 为什么每次运行程序时程序中断指针 (brk/sbrk) 都不同?

涉及指针的 C 程序输出

c++ - 使用结构体指针显示一维数组