JC Nunez
JC Nunez

Reputation: 187

Using gethostbyname

I am just starting to program using C . This should be a simple program but I am getting a segmentation fault. I would appreciate any hlep

Regards,

Juan

#include <string.h>

#include <stdio.h>
#include <stdlib.h>
#include<errno.h>
#include<netdb.h>
#include<sys/socket.h>
#include<netinet/in.h>


int main(int argc, char **argv)
{

  struct hostent *hp;
  struct in_addr **addr_list; 

  if ((hp = gethostbyname("www.yahoo.ca")) == NULL)
  {
    printf("gethostbyname() failed\n");
  }
  else
  {
    printf("Official name = %s\n", hp->h_name);

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

    unsigned int i = 0;
    while (addr_list[i] != NULL)
    {
      printf("%s\n",inet_ntoa(*((struct in_addr *)hp->h_addr)));
      i++;

    }
  }
}

Here is how the program is called:

administrator@ubuntu:~/Documents$ ./a.out
Official name = any-rc.a01.yahoodns.net
Segmentation fault (core dumped)
administrator@ubuntu:~/Documents$ 

Upvotes: 2

Views: 1663

Answers (1)

cnicutar
cnicutar

Reputation: 182619

Instead of hp->h_addr you probably want:

printf("%s\n", inet_ntoa(*addr_list[i]));

As a side note, gethostbyname is obsolescent: your should use getaddrinfo. As you'll notice, the newer version of the standard doesn't even mention gethostbyname.

Upvotes: 3

Related Questions