C/C++获取本机IP地址

75 篇文章 0 订阅
/* 编译环境: visual c++ */
  1. #include <stdio.h>
  2. #include <winsock2.h>
  3. #pragma comment(lib,"ws2_32.lib")
  4. int doit(intchar **)
  5. {
  6.     char host_name[255];
  7.     //获取本地主机名称 
  8.     if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {
  9.         printf("Error %d when getting local host name./n", WSAGetLastError());
  10.         return 1;
  11.     }
  12.     printf("Host name is: %s/n",  host_name);
  13.     //从主机名数据库中得到对应的“主机” 
  14.     struct hostent *phe = gethostbyname(host_name);
  15.     if (phe == 0) {
  16.         printf("Yow! Bad host lookup.");
  17.         return 1;
  18.     }
  19.     //循环得出本地机器所有IP地址 
  20.     for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
  21.         struct in_addr addr;
  22.         memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
  23.         printf("Address %d : %s/n" , i, inet_ntoa(addr));
  24.     }
  25.    
  26.     return 0;
  27. }
  28. int main(int argc, char *argv[])
  29. {
  30.     WSAData wsaData;
  31.     if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
  32.         return 255;
  33.     }
  34.     int retval = doit(argc, argv);
  35.     WSACleanup();
  36.     return retval;
  37. }

<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值