首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

用gethostbyaddr获取搜狐主机时遇到的奇怪有关问题

2012-04-19 
用gethostbyaddr获取搜狐主机时遇到的奇怪问题主程序voidGetHostInfoByAddr(constchar*addr){hostent*phos

用gethostbyaddr获取搜狐主机时遇到的奇怪问题
主程序

void   GetHostInfoByAddr(const   char   *addr)
{
hostent   *phost=NULL;
unsigned   long   u_ip=inet_addr(addr);
phost=gethostbyaddr((char   *)&u_ip,4,AF_INET);
cout < <WSAGetLastError() < <endl;
if   (phost==NULL)
{
cerr < < "get   host   info                                     failed---- " < <GetLastError() < <endl;
return;
}
cout < <phost-> h_name < <endl;//报错
return;
}


int   main()
{
WSADATA   wsadata;
WSAStartup(MAKEWORD(2,2),&wsadata);
        //GetHostInfoByAddr( "202.102.14.141 ");
GetHostInfoByAddr( "218.30.66.201 ");//搜狐IP,PING得到
WSACleanup();
system( "pause ");
return   0;
}

WSAGetLastError()返回值为0,且phost也不为空,表明函数调用成功。
但输出主机名时却报“0x00421940指令引用的 '0xffff305c '内存,该内存不能为 "read "
这是为什么啊?
如果说gethostbyaddr只能获取局域网的主机名,但我用202.102.14.141却又能正确取到主机,请验证一下我的代码,多谢。

[解决办法]
请看 MSDN 文档资料,WSAGetLastError()返回值为0 并不意味着所请求的地址一定有对应的 host name,如果 WSAGetLastError() == 11001,则表明没有host name, 所以有访问违例.

请看 msdn example code:


//----------------------
// Declare and initialize variables
hostent* remoteHost;
char* host_name;
unsigned int addr;

//----------------------
// User inputs name of host
printf( "Input name of host: ");
host_name = (char*) malloc(sizeof(char*)*16);
fgets(host_name, 16, stdin);

// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
if (isalpha(host_name[0])) { /* host address is a name */
host_name[strlen(host_name)-1] = '\0 '; /* NULL TERMINATED */
remoteHost = gethostbyname(host_name);
}
else {
addr = inet_addr(host_name);
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}

if (WSAGetLastError() != 0) {
if (WSAGetLastError() == 11001)
printf( "Host not found...\nExiting.\n ");
}
else
printf( "error#:%ld\n ", WSAGetLastError());

// The remoteHost structure can now be used to
// access information about the host

热点排行