1. 程式人生 > >獲取本機IP及在本機IP的基礎上自增1(只針對有一個IP的機器)

獲取本機IP及在本機IP的基礎上自增1(只針對有一個IP的機器)

turn else data 返回 主機名 add cleanup done get

1、獲取本機IP

 1 char* getLocalIP()
 2 {
 3     WSADATA wsaData;
 4     int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
 5     if (err != 0)
 6     {
 7         OUTINFO_1_PARAM("ASTSWSAStartup執行錯誤%d\n",err);
 8         return NULL;
 9     }
10     //獲取主機名
11     char szHostName[256] = {0};
12     int nRetCode;
13 nRetCode = gethostname(szHostName,sizeof(szHostName) ); 14 if (nRetCode != 0) 15 { 16 OUTINFO_0_PARAM("ASTS獲取主機名稱失敗\n"); 17 WSAGetLastError(); 18 WSACleanup(); 19 return NULL; 20 } 21 22 //獲取本機IP 23 char* lpLocalIP; 24 PHOSTENT hostinfo; 25
hostinfo = gethostbyname(szHostName); 26 if (hostinfo != NULL) 27 { 28 lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list); 29 OUTINFO_1_PARAM("ASTS主機名: %s\n", szHostName); 30 OUTINFO_1_PARAM("ASTS本地IP: %s\n", lpLocalIP); 31 32 WSACleanup();
33 return lpLocalIP; 34 } 35 else 36 { 37 WSACleanup(); 38 return NULL; 39 } 40 }

2、獲取本機IP並在本機IP的基礎上增加1

 1 char* getAddOneIP()
 2 {
 3     WSADATA wsaData;
 4     int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
 5     if (err != 0)
 6     {
 7         OUTINFO_1_PARAM("ASTSWSAStartup執行錯誤%d\n",err);
 8         return NULL;
 9     }
10     //獲取主機名
11     char szHostName[256] = {0};
12     int nRetCode;
13     nRetCode = gethostname(szHostName,sizeof(szHostName) );
14     if (nRetCode != 0)
15     {
16         OUTINFO_0_PARAM("ASTS獲取主機名稱失敗\n");
17         WSAGetLastError(); 
18         WSACleanup();
19         return NULL; 
20     }
21 
22     //獲取本機IP
23     char* lpLocalIP;
24     PHOSTENT hostinfo;
25     hostinfo = gethostbyname(szHostName);
26     if (hostinfo != NULL)
27     {
28         lpLocalIP = inet_ntoa(*(struct in_addr*)*hostinfo->h_addr_list);
29         OUTINFO_1_PARAM("ASTS主機名: %s\n", szHostName);
30         OUTINFO_1_PARAM("ASTS本地IP: %s\n", lpLocalIP);
31 
32         struct in_addr nextIP = {0};
33         memcpy(&nextIP, *hostinfo->h_addr_list, sizeof(nextIP));
34         nextIP.s_impno ++;        //下一個IP
35         char * lpNextIP = inet_ntoa(nextIP);
36         OUTINFO_1_PARAM("ASTS返回出去的IP地址: %s\n", lpNextIP);
37         WSACleanup();
38         return lpNextIP;
39     }
40     else
41     {
42         WSACleanup();
43         return NULL;
44     }
45 }

獲取本機IP及在本機IP的基礎上自增1(只針對有一個IP的機器)