一些重要的网络结构体ifconf, ifreq,sockaddr,caddr_t

ifconf, ifreq,sockaddr,caddr_t

 

//提示:结构体设计的非常规范,强烈推荐

 

/* Interface request structure used for socket ioctl's. All interface

    ioctl's must have parameter definitions which begin with ifr_name.

    The remainder may be interface specific. */

 

struct ifreq

{

#ifndef IFNAMSIZ

#define IFNAMSIZ    16

#endif

char  ifr_name[IFNAMSIZ];

union {

struct sockaddr ifru_addr;

struct sockaddr ifru_dstaddr;

struct sockaddr ifru_broadaddr;

__ulong32_t ifru_flags;

int   ifru_metric;

CADdr_t ifru_data;

u_short ifru_site6;

__ulong32_t  ifru_mtu;

int   ifru_baudrate;

} ifr_ifru;

 

//Following Macros are provided for convenIEnce

#define ifr_addr    ifr_ifru.ifru_addr   /* address */

#define ifr_dstaddr ifr_ifru.ifru_dstaddr  /* other end of p-to-p link */

#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */

#define ifr_flags ifr_ifru.ifru_flags   /* flags */

#define ifr_metric   ifr_ifru.ifru_metric  /* metric */

#define ifr_data    ifr_ifru.ifru_data   /* for use by interface */

#define ifr_site6 ifr_ifru.ifru_site6   /* IPv6 site index */

#define ifr_mtu ifr_ifru.ifru_mtu    /* mtu of interface */

#define ifr_isno    ifr_ifru.ifru_data   /* pointer to if_netopts */

#define ifr_baudrate  ifr_ifru.ifru_baudrate /* baudrate of interface */

};

 

 

/* Structure used in SIOCGIFCONF request. Used to retrieve interface

    configuration for machine (useful for programs which must know all

    networks accessible). */

 

struct ifconf

{

int   ifc_len;        /* size of associated buffer */

 

union

{

caddr_t ifcu_buf;

struct ifreq *ifcu_req;

} ifc_ifcu;

 

Following macros are provided for convenience

#define ifc_buf ifc_ifcu.ifcu_buf    /* buffer address */

#define ifc_req ifc_ifcu.ifcu_req    /* array of structures returned */

};

 

 

 

SIOCGIFADDR:获取接口地址,检索特定接口的地址

SIOCSIFADDR:设置接口地址。ifr.ifr_addr 字段返回地址。

SIOCGIFCONF:获取所有配置接口的信息,返回系统中配置的所有接口的配置信息

以上介绍转自:http://hi.baidu.com/leezongfanblog/blog/item/a86a564583934a88b3b7dc0e.html

 

struct sockaddr

{

       unsigned short sa_family; /* 地址族, AF_xxx */

       char sa_data[14]; /* 14字节的协议地址*/

};

 

typedef void *caddr_t;

处理网络接口程序的初始步骤之一就是从内核获取配置在系统中的所有接口。代码如下:

 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        return(-1);
    }

    struct ifreq buf[16];
    struct ifconf ifc;    
    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = (caddr_t)buf;
    
    ioctl(sockfd, SIOCGIFCONF, (char *)&ifc);
    
    int intr = ifc.ifc_len / sizeof(struct ifreq);
    while (intr-- > 0 && ioctl(sockfd, SIOCGIFADDR, (char *)&buf[intr]));
    close(sockfd);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值