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

原文地址:http://blog.csdn.net/langeldep/article/details/8306603

[cpp]  view plain  copy
  1. #include <stdio.h>        
  2. #include <sys/types.h>  
  3. #include <ifaddrs.h>  
  4. #include <netinet/in.h>   
  5. #include <string.h>   
  6. #include <arpa/inet.h>  
  7. #include <unistd.h>  
  8. #include <sys/types.h>  
  9. #include <string.h>  
  10. #include <stdlib.h>  
  11. #include <stdlib.h>  
  12. #include <time.h>  
  13. #include <sys/vfs.h>  
  14. #include <stdio.h>  
  15. #include <signal.h>  
  16. #include <sys/stat.h>  
  17. #include <sys/socket.h>  
  18. #include <netinet/in.h>  
  19. #include <arpa/inet.h>  
  20. #include <netdb.h>  
  21.   
  22.   
  23. int main (int argc, const char * argv[])   
  24. {  
  25.   
  26.     struct ifaddrs * ifAddrStruct=NULL;  
  27.     void * tmpAddrPtr=NULL;  
  28.   
  29.     getifaddrs(&ifAddrStruct);  
  30.   
  31.     while (ifAddrStruct!=NULL)   
  32.     {  
  33.         if (ifAddrStruct->ifa_addr->sa_family==AF_INET)  
  34.         {   // check it is IP4  
  35.             // is a valid IP4 Address  
  36.             tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;  
  37.             char addressBuffer[INET_ADDRSTRLEN];  
  38.             inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);  
  39.             printf("%s IPV4 Address %s\n", ifAddrStruct->ifa_name, addressBuffer);   
  40.         }  
  41.         else if (ifAddrStruct->ifa_addr->sa_family==AF_INET6)  
  42.         {   // check it is IP6  
  43.             // is a valid IP6 Address  
  44.             tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;  
  45.             char addressBuffer[INET6_ADDRSTRLEN];  
  46.             inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);  
  47.             printf("%s IPV6 Address %s\n", ifAddrStruct->ifa_name, addressBuffer);   
  48.         }   
  49.         ifAddrStruct = ifAddrStruct->ifa_next;  
  50.     }  
  51.     return 0;  
  52. }  


编译

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



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值