Search code examples
chostgethostbyname

gethostbyname() not working


I am trying to find my source's IP yet it won't work.

void getSourceIp(struct hostent *sourceHost, struct ip *ipStruct)
{
    char sourceName[100];

    if (gethostname(sourceName,sizeof(sourceName)) < 0)
    {
        perror("Error in function gethostname().\n");
        exit(EXIT_FAILURE);
    }

    if ((sourceHost = gethostbyname(sourceName)) == NULL)
    {
        std::cout << "The source " << sourceName << " is unknown.\n";
        exit(EXIT_FAILURE);
    }

    ipStruct->ip_src = (*(struct in_addr *) sourceHost->h_addr_list);
    std::cout << "IP Address: " << inet_ntoa(ipStruct->ip_src);
}

MAIN function:

int main(int argc, char *argv[])
{
    struct hostent *sourceHostent       = NULL;
    struct hostent *destinationHostent  = NULL;
    struct ip *ip                       = NULL;

    getSourceIp(sourceHostent,ip);
    return 0;
}

The output I get is "The source macbook is unknown."


Solution

  • As I mentioned in the comments on the question, you're method has several issues. The first is that it that the results are not passed back to the calling function. You need to use a double pointer to do this.

    Next, the value returned from gethostbyname is allocated in static memory, so it can be overwritten the next time you call the function. You need to copy the result into your own memory. This is non-trivial because you need to deep copy it and not just malloc(sizeof(struct hosting)). The complexity of doing this is why gethostbyname is depreciated. Depending on your target platform, there are much better options to do DNS lookup.

    Even if the lookup succeeded in your code, you will get a SEGFAULT. You are passing the value NULL for ipStruct and then attempting to dereference and write to it. If you dereference a NULL pointer, you're going to have a bad time. You should spend some time to understand memory management in C using malloc and free.

    Without seeing more code, I'm not sure what you're trying to do with your struct ip. It looks like you're trying to get one or more IP addresses of the host as char *, but you've missed that target by a considerable amount. I can offer a bit more help if you can elaborate on the intent.

    This last piece is stylistic, but doing assignments in if statements is error prone and a generally bad idea. You should get out of the habit of doing it.