代码实现
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
struct hostent *he;
char **alias;
if(argc < 2)
{
printf("Usage: %s name | IP", argv[0]);
exit(-1);
}
argv++;
for( ; *argv != NULL; argv++)
{
/*·´ÏòÓòÃû½âÎöº¯Êýgethostbyaddr
* ½«IP½âÎöΪÖ÷»úÃû
* ÐèÒªÏȵôÓÃinet_aton»òinet_pton*/
if(inet_aton(*argv, &addr.sin_addr)!=0)
{
he = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
printf("address information of IP %s: \n", *argv);
}
/*ÓòÃû½âÎöº¯Êýgethostbyname*/
else
{
he = gethostbyname(*argv);
printf("address information of host %s: \n", *argv);
}
if(he == NULL)
{
printf("no address information of %s\n", *argv);
continue;
}
printf("Official host name: %s\n", he->h_name);
printf("name aliases:");
for(alias = he->h_aliases; *alias != NULL; alias++)
{
printf("%s ", *alias);
}
printf("\nIP address: ");
for(alias = he->h_addr_list; *alias != NULL; alias++)
{
printf("%s\n", inet_ntoa( *(struct in_addr *)(*alias)));
}
}
}
运行示例