重点是明白结构体ifconf与ifreq的用法
#include <stdio.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#define BUFSIZE 128
int main(void)
{
int sock_fd;
struct ifconf conf;
struct ifreq *ifr;
struct sockaddr_in *sin;
char buff[BUFSIZE];
int num, i;
sock_fd = socket(PF_INET, SOCK_DGRAM, 0);
if(sock_fd < 0){
perror("socket");
return -1;
}
conf.ifc_len = BUFSIZE;
conf.ifc_buf = buff;
ioctl(sock_fd, SIOCGIFCONF, &conf);
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;
for(i = 0; i < num; i++){
sin = (struct sockaddr_in *)(&ifr->ifr_addr);
ioctl(sock_fd, SIOCGIFFLAGS, ifr);
if(((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP)){
printf("%s (%s)\n", ifr->ifr_name, inet_ntoa(sin->sin_addr));
}
ifr++;
}
}