可以读出本地设备的IP地址,主要是结构体struct ifreq的成员了解,和ioctl的使用。
下面是具体的代码片段:
#include
#include
#include
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
");
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
");
return -1;
}
sin = (struct sockaddr_in *)&ifr_ip.ifr_addr;
strcpy(pcLocalIp, inet_ntoa(sin->sin_addr));
LOGINFO("local ip :%s
", pcLocalIp);
close(sockGetIp);
return 0;
}