gpt4 book ai didi

c - 网络编程通过c编译执行但不打印IP地址...!

转载 作者:太空宇宙 更新时间:2023-11-04 02:58:44 25 4
gpt4 key购买 nike

这里包括我编写的代码代码编译并执行但 ip 地址没有打印出来,而是得到以下输出。我已经包含了下面的代码,请帮助我。

  //This is the executed code printed out  
-Inspiron-1318:~$ ./com2 google.com
Networks use Big Endian order

This machine uses Little Endian


google.com to
// here I need to print the ip addresses but I am unable to//

这是我写的代码;请帮我找出我的错误:

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

void checkEndian()
{
uint32_t a=0x10de7623;
uint32_t b = ntohl(a);
if(b == a)
{
printf("This machine uses Big Endian\n");
}
else if(b ==0x2376de10 )
{
printf("\nThis machine uses Little Endian\n");
}
else
{
printf("This machine uses Other Endian\n");
}
}

int main(int argc,char* argv[])
{
printf("Networks use Big Endian order\n");
checkEndian();

if(argc<2)
{
printf("expected a name for resolving");
exit(1);
}

char *name=argv[1];
char ip[100];

name_ip(name , ip);
printf("%s to %s\n",name,ip);
}

int name_ip(char *name,char *ip)
{
struct addrinfo hints , *answer , *h;
char buf[1024];

memset(&hints,0,sizeof hints);

hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

int error = getaddrinfo(name, NULL, &hints, &answer);

if(error!=0)
{
fprintf(stderr,"\n error in getaddrinfo: %s\n",gai_strerror(error));
exit(EXIT_FAILURE);
}

for(h = answer; h != NULL; h = h->ai_next)
{
if(h->ai_family=AF_INET)
{
struct sockaddr_in *x;

x=(struct sockaddr_in *)h->ai_addr;

//// this inet_ntop is the root of whole problem//
inet_ntop(h->ai_family,&(((struct sockaddr_in *)h->ai_addr)->sin_addr),buf,1024);

}

if(hints.ai_family=AF_INET6)
{
struct sockaddr_in6 *x;

x=(struct sockaddr_in6*)h->ai_addr;
// this inet_ntop is the root of whole problem//

inet_ntop(h->ai_family,&(((struct sockaddr_in6 *)h->ai_addr)->sin6_addr),buf,1024);
}
printf("%s\n",ip);
}

freeaddrinfo(answer);

return 0;
}

最佳答案

这是一个错误,出现了两次:

if(h->ai_family=AF_INET)

因为它是一个赋值,而不是相等检查。使用 == 代替:

if(h->ai_family==AF_INET)

此外,ip 永远不会填充到函数 name_ip() 中。

关于c - 网络编程通过c编译执行但不打印IP地址...!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14540516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com