C++获取本机IP等信息

运行环境:VS2008,win7,代码来源于MSDN,相关函数可以查看MSDN中的函数定义。。

代码如下:

 1 #include <winsock2.h>
 2 #include <ws2tcpip.h>
 3 #include <stdio.h>
 4 #include <windows.h>
 5 #pragma comment(lib, "ws2_32.lib")
 6 
 7 int main(int argc, char **argv)
 8 {
 9 
10     //-----------------------------------------
11     // Declare and initialize variables
12     WSADATA wsaData;
13     int iResult;
14 
15     DWORD dwError;
16     int i = 0;
17 
18     struct hostent *remoteHost;
19     char *host_name;
20     struct in_addr addr;
21 
22     char **pAlias;
23     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
24     if (iResult != 0) {
25         printf("WSAStartup failed: %d\n", iResult);
26         return 1;
27     }
28 
29     host_name = new char[100];
30     int index = gethostname(host_name,strlen(host_name));
31     if (0 != index)
32     {
33         printf("Error\n");
34     }
35 
36     printf("Calling gethostbyname with %s\n", host_name);
37     remoteHost = gethostbyname(host_name);
38 
39     if (remoteHost == NULL) {
40         dwError = WSAGetLastError();
41         if (dwError != 0) {
42             if (dwError == WSAHOST_NOT_FOUND) {
43                 printf("Host not found\n");
44                 return 1;
45             } else if (dwError == WSANO_DATA) {
46                 printf("No data record found\n");
47                 return 1;
48             } else {
49                 printf("Function failed with error: %ld\n", dwError);
50                 return 1;
51             }
52         }
53     } else {
54         printf("Function returned:\n");
55         printf("\tOfficial name: %s\n", remoteHost->h_name);
56         for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
57             printf("\tAlternate name #%d: %s\n", ++i, *pAlias);
58         }
59         printf("\tAddress type: ");
60         switch (remoteHost->h_addrtype) {
61         case AF_INET:
62             printf("AF_INET\n");
63             break;
64         case AF_NETBIOS:
65             printf("AF_NETBIOS\n");
66             break;
67         default:
68             printf(" %d\n", remoteHost->h_addrtype);
69             break;
70         }
71         printf("\tAddress length: %d\n", remoteHost->h_length);
72 
73         i = 0;
74         if (remoteHost->h_addrtype == AF_INET)
75         {
76             while (remoteHost->h_addr_list[i] != 0) {
77                 addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
78                 printf("\tIP Address #%d: %s\n", i, inet_ntoa(addr));
79             }
80         }
81         else if (remoteHost->h_addrtype == AF_NETBIOS)
82         {   
83             printf("NETBIOS address was returned\n");
84         }   
85     }
86 
87     return 0;
88 }

C++获取本机IP等信息,布布扣,bubuko.com

C++获取本机IP等信息

上一篇:【python】升序查找100内最大平方数的方法


下一篇:Spring 和 filter