1、Linux平台
void get_ips_by_name(string domain,vector<string>& ips)
{
ips.clear();
size_t i;
struct hostent hostbuf;
hostent* pHost= &hostbuf;
char hostBuf[1024];
size_t buffLen = sizeof(hostBuf);
int ret;
int errCode;
ret = gethostbyname_r(domain.c_str(), pHost, hostBuf, buffLen, &pHost, &errCode);
if(0 != ret)
{
return ;
}
else
{
if (!pHost)
{
return ;
}
for(i = 0; pHost!= NULL && pHost->h_addr_list[i] != NULL; i++)
{
struct in_addr* pAddr = (in_addr*)(pHost->h_addr_list[i]);
char str_ip[20] = {0};
inet_ntop(AF_INET, (const void *)(&(pAddr->s_addr)), str_ip, 20);
ips.push_back(str_ip);
}
}
}
2、iOS平台
void get_ips_by_name(string domain,vector<string>& ips)
{
ips.clear();
char szIp[32];
struct hostent* hosts = gethostbyname(domain.c_str());
if (hosts)
{
for(int i = 0; hosts!= NULL && hosts->h_addr_list[i] != NULL; i++)
{
struct in_addr* pAddr = (in_addr*)(hosts->h_addr_list[i]);
char str_ip[20] = {0};
inet_ntop(AF_INET, (const void *)(&(pAddr->s_addr)), str_ip, 20);
ips.push_back(str_ip);
}
}
}
3、Windows平台
void get_ips_by_name(string domain,vector<string>& ips)
{
HOSTENT *hosts;
char szIp[32];
hosts=gethostbyname(domain.c_str());
if(hosts!=0)
{
char ** ppAddr = hosts->h_addr_list ;
while (*ppAddr != NULL)
{
strcpy(szIp,inet_ntoa(*(LPIN_ADDR)*(ppAddr)));
ips.push_back(szIp);
ppAddr++;
}
}
}