C Linux网络编程:getaddrinfo()得到错误结果
这是一个简单的程序,我写它是为了找出一个域的所有C Linux网络编程:getaddrinfo()得到错误结果,c,linux,sockets,getaddrinfo,C,Linux,Sockets,Getaddrinfo,这是一个简单的程序,我写它是为了找出一个域的所有记录 我做到了,既没有错误也没有警告 然后我运行它,我只发现它提供了错误的IP,例如: /a.out www.google.com 2.0.0.0 2.0.0.0 这是我的代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h>
记录
我做到了,既没有错误也没有警告
然后我运行它,我只发现它提供了错误的IP,例如:
/a.out www.google.com
2.0.0.0
2.0.0.0
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
struct addrinfo addrC;
struct addrinfo *addrL;
struct addrinfo *temp;
memset(&addrC, 0, sizeof(addrC));
addrC.ai_family = AF_INET;
addrC.ai_socktype = SOCK_STREAM;
addrC.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(argv[1], "http", &addrC, &addrL) != 0)
{
perror("getaddrinfo!");
exit(1);
}
for (temp = addrL; temp != NULL; temp = temp->ai_next)
{
char addrBuf[BUFSIZ];
void *addrCount = &((struct sockaddr_in*)temp)->sin_addr;
inet_ntop(temp->ai_addr->sa_family, addrCount, addrBuf, sizeof(addrBuf));
printf("%s\n", addrBuf);
}
for (temp = addrL; temp != NULL; temp = addrL)
{
addrL = temp->ai_next;
free(temp);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
结构addrinfo addrC;
结构addrinfo*addrL;
结构addrinfo*temp;
memset(&addrC,0,sizeof(addrC));
addrC.ai_family=AF_INET;
addrC.ai_socktype=SOCK_流;
addrC.ai_协议=IPPROTO_TCP;
if(getaddrinfo(argv[1]、“http”、&addrC、&addrL)!=0)
{
佩罗尔(“getaddrinfo!”);
出口(1);
}
对于(temp=addrL;temp!=NULL;temp=temp->ai_next)
{
char addrBuf[BUFSIZ];
void*addrCount=&((结构sockaddr_in*)temp)->sin_addr;
inet_ntop(临时->ai_地址->sa_系列,地址计数,地址计数,大小(地址计数));
printf(“%s\n”,addrBuf);
}
对于(temp=addrL;temp!=NULL;temp=addrL)
{
addrL=temp->ai_next;
免费(临时);
}
返回0;
}
为什么??如何更正它?如果指针在循环内投射时出错,则应该是:
void *addrCount = &((struct sockaddr_in*)temp->ai_addr)->sin_addr;
否则,您正在读取垃圾并将垃圾传递到inet\u ntop
,因此您会得到垃圾:)另一个答案是正确的,但我建议使用getnameinfo
(使用NI\u NUMERICHOST)而不是inet\u ntop
。那你一开始就不会犯这个错误了
此外,您不应该从getaddrinfo
循环并释放结果。您可以调用freeaddrinfo
来释放整个数组。struct addrinfo
不在struct sockaddr\u中,在它们之间进行强制转换可能会产生垃圾。您可以尝试改用temp->ai_addr
,这是中的sockadr\u。(你为什么命名结果addrCount
我无法理解,它是一个地址,而不是任何东西的计数)。