刚开始学习socket网络编程,写了一个点对点局域网通信程序。当调用gethostbyaddr时一直出现错误11004,error lookup显示:The requested name is valid, but no data of the requested type was found.网络上搜索了很久,也没有找到解决方法。无奈之下,查看了《Windows网络与通信程序设计》中的例程,发现gethostbyaddr前有一句inet_addr调用,再次查看MSDN,终于明白,原来gethostbyaddr的第一个参数必须是网络字节顺序的。MSDN中写道:
struct HOSTENT FAR * gethostbyaddr (
const char FAR * addr,
int len,
int type
);
Parameters
addr [in] A pointer to an address in network byte order.
len [in] The length of the address.
type [in] The type of the address.
因此在调用gethostbyaddr前要把IP地址转换成网络字节顺序:
//ULONG ip;char strIP[]="###.###.###.###";
ip=inet_addr(strIP);
host=gethostbyaddr((char*)&ip,sizeof(ip),PF_INET);