c - 使用 gethostbyname

标签 c

我刚刚开始使用 C 编程。这应该是一个简单的程序,但我遇到了段错误。我将不胜感激任何帮助

问候,

胡安

#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++;

    }
  }
}

该程序的调用方式如下:

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

最佳答案

您可能需要的不是 hp->h_addr:

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

作为旁注,gethostbyname已过时:您应该使用 getaddrinfo 。您会注意到,该标准的新版本甚至没有提及 gethostbyname

关于c - 使用 gethostbyname,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15670713/

相关文章:

c++ - C++ OpenCV 2.3 中缺少 MoveWindow()

c - argv 和普通字符串数组之间的不同输出

c - 带有预处理器指令的指针

c - 为什么我要在同一个链接器调用中两次传递 obj 文件?

c - 在Windows中读写PCI BAR0寄存器

java - C 和 Java 中的后缀和前缀运算符产生不同的结果

c - 如何在 C 中将 int 转换为字符串?

c - MPLAB X 中的有效代码和编译器错误

c++ - 如何使用 Apache C 模块记录到文件

c - 连续的 scanfs,第二个不要求用户输入第二个