打印

[原创] C语言:通过IP地址查找主机名

C语言:通过IP地址查找主机名

初次写这些难免有不足之处,还望大家指出缺点

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(argc, argv)
int argc;
char **argv;
{
struct hostent *ip;
unsigned long hostname;

if (argc != 2)
{
printf("Need to specify an IP address.\n");
exit(1);
}
if ((hostname = inet_addr(argv[1])) == -1)
{
printf("Could not find %s\n", argv[1]);
exit(1);
}
if ((ip = gethostbyaddr((char *)&hostname, sizeof(long), AF_INET)) != NULL)
printf("%s is %s\n", argv[1], ip->h_name);
else
printf("Could not resolve %s\n", argv[1]);
return 0;
}
世事无常亦如此,我心欲绝随风去!

TOP

Processed in 0.029242 second(s), 5 queries, Gzip enabled.