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 }