getifaddrs()和struct ifaddrs的使用,获取本机IP

来源:互联网 发布:矩阵计算 戈卢布 pdf 编辑:程序博客网 时间:2024/05/22 02:28

 ifaddrs结构体定义如下:

C代码  收藏代码
  1. struct ifaddrs   
  2. {   
  3.     struct ifaddrs  *ifa_next;    /* Next item in list */   
  4.     char            *ifa_name;    /* Name of interface */   
  5.     unsigned int     ifa_flags;   /* Flags from SIOCGIFFLAGS */   
  6.     struct sockaddr *ifa_addr;    /* Address of interface */   
  7.     struct sockaddr *ifa_netmask; /* Netmask of interface */   
  8.     union   
  9.     {   
  10.         struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */   
  11.         struct sockaddr *ifu_dstaddr; /* Point-to-point destination address */   
  12.     } ifa_ifu;   
  13.     #define              ifa_broadaddr ifa_ifu.ifu_broadaddr   
  14.     #define              ifa_dstaddr   ifa_ifu.ifu_dstaddr   
  15.     void            *ifa_data;    /* Address-specific data */   
  16. };   

    ifa_next指向链表的下一个成员;ifa_name是接口名称,以0结尾的字符串,比如eth0,lo;ifa_flags是接口的标识位(比如当IFF_BROADCAST或IFF_POINTOPOINT设置到此标识位时,影响联合体变量ifu_broadaddr存储广播地址或ifu_dstaddr记录点对点地址);ifa_netmask存储该接口的子网掩码;结构体变量存储广播地址或点对点地址(见括弧介绍ifa_flags);ifa_data存储了该接口协议族的特殊信息,它通常是NULL(一般不关注他)。

    函数getifaddrs(int getifaddrs (struct ifaddrs **__ifap))获取本地网络接口信息,将之存储于链表中,链表头结点指针存储于__ifap中带回,函数执行成功返回0,失败返回-1,且为errno赋值。
    很显然,函数getifaddrs用于获取本机接口信息,比如最典型的获取本机IP地址。

0 0