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

来源:互联网 发布:淘宝上的电脑能买吗 编辑:程序博客网 时间:2024/05/17 09:28
/* 编译环境: 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"><!--google_ad_client = "pub-3555979289815451";google_ad_slot = "0437120238";google_ad_width = 468;google_ad_height = 60;//--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

原创粉丝点击