Linux中读出本地设备的IP地址方法

可以读出本地设备的IP地址,主要是结构体struct ifreq的成员了解,和ioctl的使用。

下面是具体的代码片段:

#include <net/if.h>
#include <net/if_arp.h>
#include <sys/ioctl.h>

static int GetLocalIp(char *pcLocalIp)
{   
    int sockGetIp;
    struct sockaddr_in *sin;
    struct ifreq ifr_ip;

    
    if(NULL == pcLocalIp)
    {
        return -1;
    }

    if((sockGetIp = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        LOGINFO("socket create error\r\n");
        return -1;  
    }

    memset(&ifr_ip, 0, sizeof(ifr_ip)); 
    strncpy(ifr_ip.ifr_name, "wlan0", sizeof(ifr_ip.ifr_name) - 1);//wlan0 是指具体的网卡,有的eth0等

    if(ioctl(sockGetIp, SIOCGIFADDR, &ifr_ip) < 0)
    {
        LOGINFO("ioctl operation is error\r\n");
        return -1;
    }
    
    sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
    strcpy(pcLocalIp, inet_ntoa(sin->sin_addr));

    LOGINFO("local ip :%s\r\n", pcLocalIp);
    close(sockGetIp);

    return 0;
} 

猜你喜欢

转载自blog.csdn.net/u010299133/article/details/82987210