`

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

 
阅读更多

    ifaddrs结构体定义如下:

struct ifaddrs 
{ 
    struct ifaddrs  *ifa_next;    /* Next item in list */ 
    char            *ifa_name;    /* Name of interface */ 
    unsigned int     ifa_flags;   /* Flags from SIOCGIFFLAGS */ 
    struct sockaddr *ifa_addr;    /* Address of interface */ 
    struct sockaddr *ifa_netmask; /* Netmask of interface */ 
    union 
    { 
        struct sockaddr *ifu_broadaddr; /* Broadcast address of interface */ 
        struct sockaddr *ifu_dstaddr; /* Point-to-point destination address */ 
    } ifa_ifu; 
    #define              ifa_broadaddr ifa_ifu.ifu_broadaddr 
    #define              ifa_dstaddr   ifa_ifu.ifu_dstaddr 
    void            *ifa_data;    /* Address-specific data */ 
}; 

    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地址。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics