Linux获取接口IP的方法
Linux获取接口IP的方法
#include <stdio.h>
#include <unistd.h>
#include <apra/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#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;
}