- std::string VengFuncConfig::GetLocalHostIp(void)
- {
- vector vLocalIpList;
- string sLocalIP;
- sLocalIP.clear();
- WSADATA wsaData;
- char name[155]={0};
- if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 )
- {
- if(gethostname(name,sizeof(name)) == 0)
- {
- struct hostent* pHost = gethostbyname(name);
- if (0 == pHost )
- {
- return sLocalIP;
- }
- for (int i = 0; pHost->h_addr_list[i] != 0; ++i)
- {
- struct in_addr addr;
- memcpy(&addr, pHost->h_addr_list[i], sizeof(struct in_addr));
- vLocalIpList.push_back(inet_ntoa(addr));
- }
- }
- WSACleanup( );
- }
- //所有的IP地址都在vLocalIpList中
- int nLength = vLocalIpList.size();
- //优先获取10.10.子网IP
- for(int i=0;i < nLength;i++)
- {
- if (vLocalIpList[i].find("10.10.") != -1)
- {
- sLocalIP = vLocalIpList[i];
- }
- }
- //如没有子网IP,则获取外网IP
- if (sLocalIP.empty())
- {
- for(int i=0;i < nLength;i++)
- {
- if (vLocalIpList[i].find("192.168.") == -1)
- {
- sLocalIP = vLocalIpList[i];
- }
- }
- }
- return sLocalIP;
- }
转载于:https://blog.51cto.com/venglu/1185204