下面代码很不完善,比如缺少头文件引用等,“日后”再进行优化修改。

    1. // 解析域名获取ip地址
    2. void CMX_UpdateUtils::parseUpdateSvrDomain( const char* domainStr )
    3. {
    4. if( !domainStr || domainStr == "" )
    5. {
    6. LogDebug( "invalid domain name." );
    7. return;
    8. }
    9. m_vIPsDomain.clear();
    10. #ifdef CMX_WIN_COMPILE
    11. struct hostent* h = gethostbyname( domainStr );
    12. if( h != NULL )
    13. {
    14. unsigned char* p = nullptr;
    15. for( int i = 0; h->h_addr_list[i]; i++ )
    16. {
    17. p = (unsigned char*)h->h_addr_list[i];
    18. char ip[16] = { 0 };
    19. sprintf( ip, "%u.%u.%u.%u", p[0], p[1], p[2], p[3] );
    20. m_vIPsDomain.push_back( ip );
    21. }
    22. }
    23. #else
    24. struct addrinfo * result;
    25. struct addrinfo * tmpIterator;
    26. struct sockaddr_in *tmpIPV4;
    27. struct sockaddr_in6 *tmpIPV6;
    28. int error;
    29. struct addrinfo hints;
    30. memset( &hints, 0, sizeof(hints) );
    31. //hints.ai_family = AF_UNSPEC;
    32. hints.ai_socktype = SOCK_STREAM;
    33. //hints.ai_flags = AI_PASSIVE;/* For wildcard IP address */
    34. //hints.ai_protocol = IPPROTO_IP;/* Any protocol */
    35. error = getaddrinfo( domainStr, NULL, &hints, &result );
    36. if( error == 0 )
    37. {
    38. for( tmpIterator = result; tmpIterator != NULL; tmpIterator = tmpIterator->ai_next ) {
    39. switch( tmpIterator->ai_addr->sa_family ) {
    40. case AF_INET:
    41. {
    42. char ipv4Buf[32];
    43. tmpIPV4 = (struct sockaddr_in*)tmpIterator->ai_addr;
    44. inet_ntop(AF_INET, &tmpIPV4->sin_addr, ipv4Buf, 32);
    45. LogDebug( StringUtils::format( "get ip4[%s] from domain[%s]", ipv4Buf, domainStr ) );
    46. m_vIPsDomain.push_back( ipv4Buf );
    47. }
    48. break;
    49. case AF_INET6:
    50. {
    51. char ipv6Buf[64];
    52. tmpIPV6 = (struct sockaddr_in6*)tmpIterator->ai_addr;
    53. inet_ntop( AF_INET6, &tmpIPV6->sin6_addr, ipv6Buf, 64 );
    54. LogDebug( StringUtils::format( "get ip6[%s] from domain[%s]", ipv6Buf, domainStr ) );
    55. m_vIPsDomain.push_back( ipv6Buf );
    56. }
    57. break;
    58. default:
    59. break;
    60. }
    61. }
    62. freeaddrinfo( result );
    63. }
    64. #endif
    65. //输出日志
    66. if( m_vIPsDomain.size() > 0 )
    67. {
    68. std::vector<std::string> justOne;
    69. justOne.push_back( m_vIPsDomain[0] );
    70. m_vIPsDomain = justOne;
    71. LogDebug( StringUtils::format( "the ouput of parsing domain(%s) is:", domainStr ) );
    72. for( int i = 0; i < (int)m_vIPsDomain.size(); i++ )
    73. {
    74. LogDebug( m_vIPsDomain[i] );
    75. }
    76. }
    77. else
    78. {
    79. LogDebug( StringUtils::format( "the ouput of parsing domain(%s) is empty", domainStr ) );
    80. }
    81. }