1

这里包括我编写的代码代码编译并执行,但 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;
}
4

1 回答 1

2

这是一个错误,其中有两种情况:

if(h->ai_family=AF_INET)

因为它是一个assignment,而不是一个相等性检查。改用==

if(h->ai_family==AF_INET)

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

于 2013-01-26T20:43:02.970 回答