0

I was trying to get the IP address from an URL but gethostbyname always says Unknown host. Hope someone can point out my fault. Here is my code

char *handleAddress(char *URL)
{
    struct hostent *he;
    struct in_addr **addr_list;
    int i;
    char *ip = NULL;
    printf("Search IP for this = %s\n", URL);
    if ((he = gethostbyname(URL)) == NULL) // get the host info
    {
        herror("gethostbyname");
        ip = "No Such DNS";
        return ip;
    }

    addr_list = (struct in_addr **)he->h_addr_list;

    for (i = 0; addr_list[i] != NULL; i++) //Return the first one;
    {
        strcpy(ip, inet_ntoa(*addr_list[i]));
        return ip;
    }
}

Expected: URL: www.google.com return IP: 173.194.72.106

CKJ
  • 9
  • 3
  • 2
    Calling host name as `URL` looks weird. What are you passing for that? Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – MikeCAT Jun 24 '21 at 05:26
  • Also your code has this problem (not duplicate): [c - Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer - Stack Overflow](https://stackoverflow.com/questions/37549594/crash-or-segmentation-fault-when-data-is-copied-scanned-read-to-an-uninitializ) – MikeCAT Jun 24 '21 at 05:26
  • 1
    If `URL` is really a URL, then this won't work. You need to pass a host name, not a URL. E.g., you need to pass `amazon.com`, not `http://amazon.com`. – Tom Karzes Jun 24 '21 at 05:37
  • 3
    Have you read the man page? *"The `gethostbyname*()`, `gethostbyaddr*()`, `herror()`, and `hstrerror()` functions are obsolete. Applications should use `getaddrinfo(3)`, `getnameinfo(3)`, and `gai_strerror(3)` instead."* You may want to work through [Beej's Guide to Network Programming](https://beej.us/guide/bgnet/) for handling the transition. – David C. Rankin Jun 24 '21 at 05:44
  • @CKJ - What does `nslookup www.google.com` say? – Armali Jun 24 '21 at 17:50

1 Answers1

0

It was an idiotic problem. First, the URL should not have \n in the end. Second, I changed the loop to

char **he_ptr;
he_ptr = he->h_addr_list;
for (; *he_ptr != NULL; he_ptr++)
{
    return inet_ntop(he->h_addrtype, *he_ptr, buff, sizeof(buff));
}

Then, somehow it worked. I did not figure out why it worked by changing a way to iterate it.

CKJ
  • 9
  • 3