1. gethostbyname:根据主机名字得到主机信息:
struct hostent FAR *WSAAPI gethostbyname(const char FAR * name);
gethostbyaddr:根据主机地址获取主机信息:
struct hostent FAR *WSAAPI gethostbyaddr(const char FAR * addr,
int len,
int type);
2.主机信息的结构定义:
/*
* Structures returned by network data base library, taken from the
* BSD file netdb.h. All addresses are supplied in host order, and
* returned in network order (suitable for use in system calls).
*/
struct hostent {
char FAR * h_name; /* official name of host */
char FAR * FAR * h_aliases; /* alias list */
short h_addrtype; /* host address type */
short h_length; /* length of address */
char FAR * FAR * h_addr_list; /* list of addresses */
#define h_addr h_addr_list[0] /* address, for backward compat */
};
3.示例程序和运行结果:
#include <winsock2.h>
#include <stdio.h>
int DisplayHostInfo(char* pName);
#pragma comment(lib, "ws2_32.lib ")
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 0 );
if (WSAStartup(wVersionRequested , &wsaData)!=0)
{
printf("Winsock Initialization failed./n");
exit(0);
};
DisplayHostInfo("www.163.com");
}
int DisplayHostInfo(char* pName)
{
struct hostent *pHost=NULL;
BYTE ucIdx =0;
//naddr = (inet_addr("192.168.0.22"));
//pHost =gethostbyaddr((char*)&naddr,4,AF_INET);
pHost =gethostbyname(pName);
if(pHost == NULL)
{
printf("/r/ngethostbyname error!!/n/r");
return -1;
}
printf("/r/nh_name: %s",pHost->h_name);
for(ucIdx = 0; pHost->h_aliases[ucIdx]; ucIdx++)
{
printf("/r/nh_aliases[%u]: %s",ucIdx,pHost->h_aliases[ucIdx]);
}
printf("/n/rh_addrtype: %u",pHost->h_addrtype);
printf("/n/rh_length: %u",pHost->h_length);
for(ucIdx = 0; pHost->h_addr_list[ucIdx]; ucIdx++)
{
printf("/r/nh_addr_list[%u]: %s/r/n",ucIdx,inet_ntoa(*(struct in_addr*)pHost->h_addr_list[ucIdx]));
}
return 0;
}
运行结果:
DisplayHostInfo("www.163.com")获取的信息:
h_name: 163.xdwscache.glb0.lxdns.com
h_aliases[0]: www.163.com
h_aliases[1]: www.cache.wangsu.netease.com
h_aliases[2]: www.163.com.lxdns.com
h_aliases[3]: www.163.z.lxdns.com
h_addrtype: 2
h_length: 4
h_addr_list[0]: 222.88.95.169
h_addr_list[1]: 222.88.95.137