域名解析2则
下面是2则域名解析的例子
void CView::HostNameToIP(CString strhostName) //域名解析为IP地址
{
char pURL[]="http://www.163.com/";
struct hostent *hp;
int k;
char **p;
hp = gethostbyname(pURL);
if(hp==NULL) {return; }
for (p = hp->h_addr_list; *p ; p++) //循环显示所有IP
{
char *sIP;
sIP = inet_ntoa(*(struct in_addr*)*p);
CString strIP = sIP;
}
}
//域名解析出ip
//如果想获取本机ip,则把name置null
lpctstr jsocket::getipstr(char * name)
{
char szhostname[256];
if (!name)
{
if (gethostname(szhostname, sizeof(szhostname))==0)
name = szhostname;
else
return 0;
}
hostent *he;
if ((he = gethostbyname(name)) == null)
{
// if failed, try using gethostbyaddr instead
unsigned long ip = inet_addr(name);
if (ip == inaddr_none)
return null;
if ((he = gethostbyaddr((char *)&ip,sizeof(ip),af_inet)) == null)
return null;
}
return inet_ntoa (*(struct in_addr *)he->h_addr_list[0]);
}