0
#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?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
dsfa24
  • 41
  • 6

1 Answers1

3

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
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Thank you for your help.How about the two programs below? – dsfa24 Mar 30 '13 at 14:32
  • 1
    You can't just keep adding more and more questions to an existing question. I answered the question you asked. If you have more, ask a new question. I rolled back the edit so that this question is in its original form. For what it's worth the difference between the two programs is that one uses a string literal for the URL, and the other uses `argv[1]`. So presumably `argv[1]` contained something other than a URL. – David Heffernan Mar 30 '13 at 14:34
  • Sorry for that.This is my first time to use this website to solve my question so that I don't understand the rules in detail.After all,thanks for you help. – dsfa24 Mar 30 '13 at 15:10
  • That's OK. The other code was surely failing because you didn't pass a command line argument and so argv[1] was NULL. If this answers your question, you may consider accepting the answer. That's another of our conventions here. – David Heffernan Mar 30 '13 at 15:46
  • Thanks for the accept, and I hope you are on top of this all now! – David Heffernan Mar 30 '13 at 16:19