首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用gethostbyname

使用gethostbyname
EN

Stack Overflow用户
提问于 2013-03-27 22:26:23
回答 1查看 1.5K关注 0票数 2

我刚刚开始用C编程。这应该是一个简单的程序,但我得到了一个分段错误。我会很感激你的

致以敬意,

胡安

代码语言:javascript
复制
#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++;

    }
  }
}

以下是该程序的调用方式:

代码语言:javascript
复制
administrator@ubuntu:~/Documents$ ./a.out
Official name = any-rc.a01.yahoodns.net
Segmentation fault (core dumped)
administrator@ubuntu:~/Documents$ 
EN

回答 1

Stack Overflow用户

发布于 2013-03-27 22:28:58

hp->h_addr不同,您可能希望:

代码语言:javascript
复制
printf("%s\n", inet_ntoa(*addr_list[i]));

顺便提一句,gethostbyname已经过时了:您应该使用getaddrinfo。正如您所注意到的,新版本的标准甚至没有提到gethostbyname

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15670713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档