Question

#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
int main(int argc, char **argv)
{
    char *ptr = NULL;
    struct hostent *hptr = NULL;
    struct in_addr *hipaddr = NULL;
    ptr = argv[1];
    inet_aton(ptr,hipaddr);
    hptr = gethostbyaddr(hipaddr, 4, AF_INET);
    printf("official hostname:%s\n",hptr->h_name);
    return 0;
}

The running result showed that :segmentation fault (core dumped). But I don't know how to make it work .So I need some help...

I changed the code to this:

#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
int main(int argc, char **argv)
{
char *ptr = NULL;
struct hostent *hptr = NULL;
struct in_addr hipaddr ;

ptr = argv[1];
inet_aton(ptr,&hipaddr);
hptr = gethostbyaddr(&hipaddr, sizeof(hipaddr), AF_INET);
printf("official hostname:%s\n",hptr->h_name);
return 0;
}

Then it works!But why?

Was it helpful?

Solution

In the first version you pass the null pointer to inet_aton. Then inet_aton attempts to write to that address and that leads to the segfault.

inet_aton(ptr,hipaddr);//hipaddr is NULL

You need to pass a pointer to an in_addr struct when you call inet_aton. Which is what you do in the second version.

struct in_addr hipaddr;
inet_aton(ptr, &hipaddr);&hipaddr is a pointer to struct in_addr
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top