码迷,mamicode.com
首页 > 系统相关 > 详细

Linux编程获取本机IP地址

时间:2014-06-22 22:53:27      阅读:394      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   http   

使用函数getifaddrs来枚举网卡IP,其中使用到的结构体如下所示:

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赋值。

编程实现本机IP地址获取:

#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>

int main (int argc, const char * argv[]) {
    struct ifaddrs * ifAddrStruct=NULL;
    struct ifaddrs * ifa=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
            // is a valid IP6 Address
            tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
            printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
        } 
    }
    if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);
    return 0;
}
在服务器上运行,获得的结果如下图:

bubuko.com,布布扣



Linux编程获取本机IP地址,布布扣,bubuko.com

Linux编程获取本机IP地址

标签:des   style   class   blog   code   http   

原文地址:http://blog.csdn.net/wan_hust/article/details/32912889

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!