C/C++擷取本機IP地址

來源:互聯網
上載者:User
/* 編譯環境: visual c++ */
  1. #include <stdio.h>
  2. #include <winsock2.h>
  3. #pragma comment(lib,"ws2_32.lib")
  4. int doit(int, char **)
  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. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.