1. 程式人生 > >Linux下ioctl獲取介面資訊

Linux下ioctl獲取介面資訊

一、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;
}