我正在尝试阅读有关特定主机的所有信息并打印出所有信息。 我可以阅读并打印出所有地址,但我没有阅读任何ai_canonname!
首先我认为我的例子(www.google.com | www.irs.gov | ...)没有正式名称,但过了一段时间我觉得我根本没有得到任何名字。 你认为我做错了什么,或者你有一个可行的例子吗?
这是我的代码,
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <sys/time.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
struct addrinfo *result, *rp, hints;
int error;
char canonname[32][256];
int canonnum = 0;
char ip[32][64];
int ipnum = 0;
struct timeval tv;
uint64_t starttime, endtime;
if(argc<2)
{
printf("Usage: %s <address>\n", argv[0]);
return 0;
}
/* Record Start time */
gettimeofday(&tv, NULL);
starttime = tv.tv_usec;
memset(&hints, 0, sizeof(hints));
memset(canonname, 0, 32*256*sizeof(char));
memset(ip, 0, 32*64*sizeof(char));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
error = getaddrinfo(argv[1], NULL, &hints, &result);
if (error != 0)
{
if (error == EAI_SYSTEM)
{
perror("getaddrinfo");
}
else
{
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
}
return -1;
}
strcpy(canonname[0], "");
if(result->ai_canonname != NULL)
strcpy(canonname[0], result->ai_canonname);
canonnum++;
for(rp = result; rp != NULL; rp = rp->ai_next) {
if(rp !=result && rp->ai_canonname != NULL)
{
if(strcmp(rp->ai_canonname, "")!=0)
{
strcpy(canonname[canonnum],rp->ai_canonname);
canonnum++;
}
}
struct sockaddr_in *inaddr_ptr;
if (rp->ai_addr->sa_family == AF_INET)
inaddr_ptr = (struct sockaddr_in *)rp->ai_addr;
sprintf(ip[ipnum],"%s\n", inet_ntoa(inaddr_ptr->sin_addr));
ipnum++;
}
/* Gets the end time and prints out the execution time */
gettimeofday(&tv, NULL);
endtime = tv.tv_usec;
printf("Execution time: %llu milliseconds\n",(endtime - starttime)/100);
printf("Official name: %s\n", canonname[0]);
printf("Aliases:\n");
for(int i=1;i<canonnum;i++)
printf("%s\n",canonname[i]);
printf("Addresses:\n");
for(int i=0;i<ipnum;i++)
printf("%s",ip[i]);
freeaddrinfo(result);
return 0;
}
答案 0 :(得分:5)
getaddrinfo()
的规范说你应该添加:
hints.ai_flags = AI_CANONNAME;
你会得到你所要求的。
$ ./gai www.ibm.com
Execution time: 4499 milliseconds
Official name: www.ibm.com
Aliases:
Addresses:
129.42.60.216
$ ./gai www.google.com
Execution time: 248 milliseconds
Official name: www.google.com
Aliases:
Addresses:
74.125.239.50
74.125.239.49
74.125.239.48
74.125.239.52
74.125.239.51
$ ./gai www.irs.gov
Execution time: 2872 milliseconds
Official name: 63-146-70-67.dia.static.qwest.net
Aliases:
Addresses:
63.146.70.67
63.146.70.96
$ ./gai www.irs.gov
Execution time: 2299 milliseconds
Official name: 63-146-70-96.dia.static.qwest.net
Aliases:
Addresses:
63.146.70.96
63.146.70.67
$
我不确定如何改变国税局的身份。 Canonical并不像所有那样具有规范性,似乎。