linux接口信息,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

#include

#include

#include

#include

#include

#include

#include

#include

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

{

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;

}

你可能感兴趣的:(linux接口信息)