我正在尝试用IP地址89.249.207.231.获取主机信息。我知道它的存在,因为当我在浏览器的url字段中键入IP地址时,它会找到页面。这是我的C代码。
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
int main()
{
struct in_addr addr;
inet_aton("89.249.207.231", &addr);
struct hostent* esu = gethostbyaddr((const char*)&addr),sizeof(addr), AF_INET);
printf("%s\n", esu->h_name);
return 0;
}当我编译并运行它时,它会给出“分段错误”。我无法理解我的代码的问题。
如有任何提示和建议,将不胜感激。
谢谢!
发布于 2015-02-17 17:54:04
即使主机存在,也可能无法提取其主机名。
例如,下面的代码,如果没有您使用的不推荐的函数,则会给出结果host=google-public-dns-a.google.com,而使用主机地址则会给出could not resolve hostname。
造成分段错误的原因是,esu是NULL,因为函数无法通过给定的IP解析主机名。
以下是代码:
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
struct sockaddr_in sa; /* input */
socklen_t len; /* input */
char hbuf[NI_MAXHOST];
memset(&sa, 0, sizeof(struct sockaddr_in));
/* For IPv4*/
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("8.8.8.8");
len = sizeof(struct sockaddr_in);
if (getnameinfo((struct sockaddr *) &sa, len, hbuf, sizeof(hbuf),
NULL, 0, NI_NAMEREQD)) {
printf("could not resolve hostname\n");
}
else {
printf("host=%s\n", hbuf);
}
return 0;
}https://stackoverflow.com/questions/28566424
复制相似问题