我刚刚开始用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$ 发布于 2013-03-27 22:28:58
与hp->h_addr不同,您可能希望:
printf("%s\n", inet_ntoa(*addr_list[i]));顺便提一句,gethostbyname已经过时了:您应该使用getaddrinfo。正如您所注意到的,新版本的标准甚至没有提到gethostbyname。
https://stackoverflow.com/questions/15670713
复制相似问题