hostent是host entry的缩写,该结构记录主机的信息,包括主机名、别名、地址类型、地址长度和地址列表。之所以主机的地址是一个列表的形式,原因是当一个主机有多个网络接口时,自然有多个地址。
hostent
外文名
hostent全称
host entry记录
主机的信息包括
主机名、别名等地址
struct hostent
h_name – 地址的正式名称。
h_aliases – 空字节-地址的预备名称的指针。
h_addrtype –地址类型; 通常是AF_INET。
h_length – 地址的比特长度。
h_addr_list – 零字节-主机网络地址指针。网络字节顺序。
h_addr - h_addr_list中的第一地址。
详细资料
示例
#include
#include
#include
#include
#pragma comment(lib, "wininet.lib")
int main(int argc, char **argv)
{
//-----------------------------------------
// Declare and initialize variables
WSADATA wsaData;
int iResult;
DWORD dwError;
int i = 0;
struct hostent *remoteHost;
char *host_name;
struct in_addr addr;
char **pAlias;
// Validate the parameters
if (argc != 2) {
printf("usage: %s ipv4addressn", argv);
printf(" orn");
printf(" %s hostnamen", argv);
printf("to return the hostn");
printf(" %s 127.0.0.1n", argv);
printf("to return the IP addresses for a hostn");
printf(" %s www.tangzhigui.com n", argv);
return 1;
}
// Initialize Winsock
iResult = www.qz888.com/ WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %dn", iResult);
return 1;
}
host_name = argv;
// 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)) { /* host address is a name */
printf("Calling gethostbyname with %sn", host_name);
remoteHost = gethostbyname(host_name);
} else {
printf("Calling gethostbyaddr with %sn", host_name);
addr.s_addr = inet_addr(host_name);
if (addr.s_addr = www.qz888.com = INADDR_NONE) {
printf("The IPv4 address entered must be a legal addressn");
return 1;
} else
remoteHost = gethostbyaddr((char *) &addr, 4, AF_INET);
}
if (remoteHost == NULL) {
dwError = WSAGetLastError();
if (dwError != 0) {
if (dwError == WSAHOST_NOT_FOUND) {
printf("Host not foundn");
return 1;
} else if (dwError == WSANO_DATA) {
printf("No data record foundn");
return 1;
} else {
printf("Function failed with error: %ldn", dwError);
return 1;
}
}
} else {
printf("Function returned:n");
printf("tOfficial name: %sn", remoteHost->h_name);
for (pAlias = remoteHost->h_aliases; *pAlias != 0; pAlias++) {
printf("tAlternate name #%d: %sn", ++i, *pAlias);
}
printf("tAddress type: ");
switch (remoteHost->h_addrtype) {
case AF_INET:
printf("AF_INETn");
break;
case AF_INET6:
printf("AF_INET6n");
break;
case AF_NETBIOS:
printf("AF_NETBIOSn");
break;
default:
printf(" %dn", remoteHost->h_addrtype);
break;
}
printf("tAddress length: %dn", remoteHost->h_length);
if (remoteHost->h_addrtype == AF_INET) {
while (remoteHost->h_addr_list[i] != 0) {
addr.s_addr = *(u_long *) remoteHost->h_addr_list[i++];
printf("tIPv4 Address #%d: %sn", i, inet_ntoa(addr));
}
} else if (remoteHost->h_addrtype == AF_INET6)
printf("tRemotehost is an IPv6 addressn");
}
return 0;
}
参考资料
socket编程·布布扣