linux获取接口IP的方法
分类:计算机等级
|
更新时间:2016-07-07|
来源:转载
#include
#include
#include
#include
#include
#define IFNAMSIZ 16
struct ifreq {
char ifr_name[IFNAMSIZ]; // interface name, e.g., "eth0"
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
short ifru_flags;
int ifru_metric;
caddr_t ifru_data;
} ifr_ifru;
};
unsigned long do_ioctl_get_ipaddress(char *dev)
{
struct ifreq ifr;
int fd;
unsigned long ip;
struct in_addr tmp_addr;
strcpy(ifr.ifr_ifru.ifr_name, dev);
fd = socket(AF_INET, SOCK_DGRAM, 0);
if (ioctl(fd, SIOCGIFADDR, &ifr)) {
perror("ioctl error");
return 0;
}
close(fd);
memcpy(&ip,ifr.ifr_addr.sa_data + 2,4);
tmp_addr.s_addr=ip;
printf("%s : %s\n", dev, inet_ntoa(tmp_addr));
return ip;
}