现在的位置: 首页 > 综合 > 正文

Linux下靠谱的获取本机IP地址的C代码实现

2013年04月18日 ⁄ 综合 ⁄ 共 1359字 ⁄ 字号 评论关闭
#include <stdio.h>      
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h> 
#include <string.h> 
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
#include <time.h>
#include <sys/vfs.h>
#include <stdio.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>


int main (int argc, const char * argv[]) 
{

    struct ifaddrs * ifAddrStruct=NULL;
    void * tmpAddrPtr=NULL;

    getifaddrs(&ifAddrStruct);

    while (ifAddrStruct!=NULL) 
	{
        if (ifAddrStruct->ifa_addr->sa_family==AF_INET)
		{   // check it is IP4
            // is a valid IP4 Address
            tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            char addressBuffer[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
            printf("%s IPV4 Address %s\n", ifAddrStruct->ifa_name, addressBuffer); 
        }
		else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6)
		{   // check it is IP6
            // is a valid IP6 Address
            tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
            char addressBuffer[INET6_ADDRSTRLEN];
            inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
            printf("%s IPV6 Address %s\n", ifAddrStruct->ifa_name, addressBuffer); 
        } 
        ifAddrStruct = ifAddrStruct->ifa_next;
    }
    return 0;
}

编译

gcc -g -O0 -o showip main.c   

执行

./showip

显示如下

[root@localhost ~]# ./showip
lo IPV4 Address 127.0.0.1
eth0 IPV4 Address 192.168.1.103
lo IPV6 Address ::
eth0 IPV6 Address 0:0:fe80::20c:29ff

抱歉!评论已关闭.