获取主机信息时出现分段错误
它在高并发性调用时发生,似乎gethostbyname
的结果没有被缓存?
static int proxy_getaddr(char *HostName) { struct hostent* Host; Host=gethostbyname(HostName); if(!Host) { unsigned long int addr=inet_addr(HostName); if(addr!=-1) Host=gethostbyaddr((char*)addr,sizeof(addr),AF_INET); } ...
这是核心转储:
0x00000034f40e98b1 in gethostbyaddr () from /lib64/libc.so.6 0x000000000040182c in proxy_getaddr (HostName=0x48d75be0 "stackoverflow.com")
我该如何解决这个问题?
gethostbyaddr的第一个参数应该是指向in_addr结构的指针,而不是指向long的指针。 请参见http://pubs.opengroup.org/onlinepubs/009695399/functions/gethostbyaddr.html 。
您的代码不正确。 你传递inet_addr()
的结果, inet_addr()
转换为指针,但你真正想要的是这个的地址 :
Host = gethostbyaddr(&addr, sizeof(addr), AF_INET);
(其他注释,您应该使用in_addr_t
而不是unsigned long int
也是正确的,但这不太可能导致您的问题)。
根据此处找到的文档 ,您传递的是错误的值:
gethostbyaddr()
接受一个结构in_addr
或structin6_addr
并为你提供一个相应的主机名(如果有的话),所以它与gethostbyname()
相反。 至于参数,即使addr是char*
,你实际上也希望传入指向结构in_addr
的指针 。len
应该是sizeof(struct in_addr)
,类型应该是AF_INET
。
以下是引用网站的一些示例代码:
struct hostent *he; struct in_addr ipv4addr; struct in6_addr ipv6addr; inet_pton(AF_INET, "192.0.2.34", &ipv4addr); he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET); printf("Host name: %s\n", he->h_name); inet_pton(AF_INET6, "2001:db8:63b3:1::beef", &ipv6addr); he = gethostbyaddr(&ipv6addr, sizeof ipv6addr, AF_INET6); printf("Host name: %s\n", he->h_name);