下面代码很不完善,比如缺少头文件引用等,“日后”再进行优化修改。
// 解析域名获取ip地址void CMX_UpdateUtils::parseUpdateSvrDomain( const char* domainStr ){if( !domainStr || domainStr == "" ){LogDebug( "invalid domain name." );return;}m_vIPsDomain.clear();#ifdef CMX_WIN_COMPILEstruct hostent* h = gethostbyname( domainStr );if( h != NULL ){unsigned char* p = nullptr;for( int i = 0; h->h_addr_list[i]; i++ ){p = (unsigned char*)h->h_addr_list[i];char ip[16] = { 0 };sprintf( ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3] );m_vIPsDomain.push_back( ip );}}#elsestruct addrinfo * result;struct addrinfo * tmpIterator;struct sockaddr_in *tmpIPV4;struct sockaddr_in6 *tmpIPV6;int error;struct addrinfo hints;memset( &hints, 0, sizeof(hints) );//hints.ai_family = AF_UNSPEC;hints.ai_socktype = SOCK_STREAM;//hints.ai_flags = AI_PASSIVE;/* For wildcard IP address *///hints.ai_protocol = IPPROTO_IP;/* Any protocol */error = getaddrinfo( domainStr, NULL, &hints, &result );if( error == 0 ){for( tmpIterator = result; tmpIterator != NULL; tmpIterator = tmpIterator->ai_next ) {switch( tmpIterator->ai_addr->sa_family ) {case AF_INET:{char ipv4Buf[32];tmpIPV4 = (struct sockaddr_in*)tmpIterator->ai_addr;inet_ntop(AF_INET, &tmpIPV4->sin_addr, ipv4Buf, 32);LogDebug( StringUtils::format( "get ip4[%s] from domain[%s]", ipv4Buf, domainStr ) );m_vIPsDomain.push_back( ipv4Buf );}break;case AF_INET6:{char ipv6Buf[64];tmpIPV6 = (struct sockaddr_in6*)tmpIterator->ai_addr;inet_ntop( AF_INET6, &tmpIPV6->sin6_addr, ipv6Buf, 64 );LogDebug( StringUtils::format( "get ip6[%s] from domain[%s]", ipv6Buf, domainStr ) );m_vIPsDomain.push_back( ipv6Buf );}break;default:break;}}freeaddrinfo( result );}#endif//输出日志if( m_vIPsDomain.size() > 0 ){std::vector<std::string> justOne;justOne.push_back( m_vIPsDomain[0] );m_vIPsDomain = justOne;LogDebug( StringUtils::format( "the ouput of parsing domain(%s) is:", domainStr ) );for( int i = 0; i < (int)m_vIPsDomain.size(); i++ ){LogDebug( m_vIPsDomain[i] );}}else{LogDebug( StringUtils::format( "the ouput of parsing domain(%s) is empty", domainStr ) );}}
