1

This is a simple program, I write it to find out all of a domain's A record.

I complie it and get no errors nor warnings.

Then I run it, I only found it give wrong IP, such as:

./a.out www.google.com

2.0.0.0

2.0.0.0

This is my code:

#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;
}

Why? and how to correct it?

Waynn Lue
  • 11,344
  • 8
  • 51
  • 76
thlgood
  • 1,275
  • 3
  • 18
  • 36
  • `struct addrinfo` is not `struct sockaddr_in` and casting between them is likely to produce garbage. You can try to use `temp->ai_addr` instead, which is a `sockadr_in`. (Why do you name the result `addrCount` is beyond me, it is meant to be an address, not a count of anything). – n. m. could be an AI Mar 11 '12 at 07:53

2 Answers2

1

You have an error in your pointer casting inside the loop, it should be:

void *addrCount = &((struct sockaddr_in*)temp->ai_addr)->sin_addr;

Otherwise you are reading garbage and passing that garbage to inet_ntop, so you get garbage as a result :)

sirgeorge
  • 6,331
  • 1
  • 28
  • 33
1

The other answer is correct, but I'd recommend to use getnameinfo (using NI_NUMERICHOST) instead of inet_ntop. Then you wouldn't have had this error in the first place.

Also, you're not supposed to loop and free the result from getaddrinfo. You call freeaddrinfo to free the whole array.

Per Johansson
  • 6,697
  • 27
  • 34