概述
有时候,总想验证一些奇怪的想法,干脆就写下来,以备后查。
想法:根据域名获取对应的IP地址(gethostbyname)?
// 获取域名对应的IP地址
BOOL GetIpAddrByDomainName(LPCTSTR domain, CAtlArray<CString> & ipList)
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
assert(LOBYTE(wsadata.wVersion) == 2 && HIBYTE(wsadata.wVersion) == 2);
HOSTENT *hptr = gethostbyname(CStringA(domain));
if (NULL == hptr)
{
return FALSE;
}
assert(AF_INET == hptr->h_addrtype || AF_INET6 == hptr->h_addrtype);
BOOL exist = FALSE;
TCHAR ipStr[INET6_ADDRSTRLEN] = {0};
for (char **pptr = hptr->h_addr_list; *pptr != NULL; pptr++)
{
if (NULL != InetNtop(hptr->h_addrtype, *pptr, ipStr, sizeof(ipStr)))
{
exist = TRUE;
ipList.Add(ipStr);
}
}
return exist;
}
// 测试域名解析
void TestCase_GetIpAddrByDomainName()
{
LPCTSTR domains[] = {
_T("localhost"),
_T("baidu.com"),
_T("www.baidu.com"),
_T("1.2.3.4"),
_T("0.0.0.0"),
_T("127.0.0.1"),
_T("ABCD:EF:1:2:3:4:5:6789"),
_T("::1"),
NULL,
_T(""),
_T("this is a string.")
};
for (unsigned int i = 0; i < _countof(domains); i++)
{
CAtlArray<CString> ipList;
if (! GetIpAddrByDomainName(domains[i], ipList))
{
_tprintf_s(_T("get IP address from domain name failed. [%s] n"), domains[i]);
}
else
{
CString csIpList;
for (unsigned int k = 0; k < ipList.GetCount(); k++)
{
csIpList += ipList[k];
if (k != ipList.GetCount() - 1)
{
csIpList += _T(",");
}
}
_tprintf_s(_T("get IP address from domain name success. [%s] [%s] [%u] n"), domains[i], csIpList, ipList.GetCount());
}
}
}
执行结果:
Visual Leak Detector Version 2.5.1 installed.
get IP address from domain name success. [localhost] [127.0.0.1] [1]
get IP address from domain name success. [baidu.com] [123.125.115.110,220.181.57.216] [2]
get IP address from domain name success. [www.baidu.com] [180.97.33.108,180.97.33.107] [2]
get IP address from domain name success. [1.2.3.4] [1.2.3.4] [1]
get IP address from domain name success. [0.0.0.0] [0.0.0.0] [1]
get IP address from domain name success. [127.0.0.1] [127.0.0.1] [1]
get IP address from domain name failed. [ABCD:EF:1:2:3:4:5:6789]
get IP address from domain name failed. [::1]
get IP address from domain name success. [(null)] [172.28.206.65,192.168.233.1,192.168.43.1,192.168.111.161] [4]
get IP address from domain name success. [] [172.28.206.65,192.168.233.1,192.168.43.1,192.168.111.161] [4]
get IP address from domain name failed. [this is a string.]
No memory leaks detected.
注意:
1. 传递IPv4字符串,得到的仍然IPv4字符串。
2. 传递IPv6字符串,解析失败。
3. 传递NULL和空字符串,得到的都是本地IP地址列表。
4. baidu.com和www.baidu.com得到的IP地址列表不一样。
最后
以上就是光亮唇彩为你收集整理的验证:根据域名获取对应的IP地址(gethostbyname)?的全部内容,希望文章能够帮你解决验证:根据域名获取对应的IP地址(gethostbyname)?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复