红联Linux门户
Linux帮助

Linux下ioctl获取接口信息

发布时间:2016-07-07 10:47:03来源:linux网站作者:CodeHeng
一、ifconf和ifreq结构
//ifconf通常是用来保存所有接口信息的  
//if.h  
struct ifconf  
{  
int ifc_len; /* size of buffer */  
union  
{  
char *ifcu_buf; /* input from user->kernel*/  
struct ifreq *ifcu_req; /* return from kernel->user*/  
} ifc_ifcu;  
};  
#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */  
#define ifc_req ifc_ifcu.ifcu_req /* array of structures */
//ifreq用来保存某个接口的信息  
//if.h  
struct ifreq   
{  
char ifr_name[IFNAMSIZ];  
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;  
};  
#define ifr_addr ifr_ifru.ifru_addr  
#define ifr_dstaddr ifr_ifru.ifru_dstaddr  
#define ifr_broadaddr ifr_ifru.ifru_broadaddr  
 
二、使用示例
/************************ 
file: test.c 
funtion: get all interfaces info 
************************/  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
#include <sys/ipc.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
#include <net/if.h>  
#include <sys/types.h>  
#include <sys/ioctl.h>
unsigned char buf[512];
int main()  
{  
struct ifconf myconf;  
struct ifreq *myreq;  
int sockfd;  
int i;
myconf.ifc_len = 512;  
myconf.ifc_buf = buf;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)  
{  
perror("socket failed.\n");  
exit(1);  
}  
ioctl(sockfd, SIOCGIFCONF, &myconf);  
myreq = (struct ifreq *)buf;
printf("len: %d\n", myconf.ifc_len);  
for (i=0; i<(myconf.ifc_len/sizeof(struct ifreq)); i++)  
{  
printf("name: %s\n", myreq->ifr_name);  
printf("local addr: %s\n", inet_ntoa(((struct sockaddr_in *)&(myreq->ifr_addr))->sin_addr));  
myreq++;  
}  
close(sockfd);  
return 0;  
}
 
本文永久更新地址://m.ajphoenix.com/linux/22147.html