开发者

Segmentation fault when getting host information

It happens when called at high concurrency,it seems the result of gethostbyname is not cached ?

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);
    }
    ...
开发者_如何学运维

Here's the core dump:

0x00000034f40e98b1 in gethostbyaddr () from /lib64/libc.so.6
0x000000000040182c in proxy_getaddr (HostName=0x48d75be0 "stackoverflow.com")

How can I fix this issue?


The first parameter of gethostbyaddr is supposed to be a pointer to an in_addr structure, not a pointer to a long. See http://pubs.opengroup.org/onlinepubs/009695399/functions/gethostbyaddr.html.


Your code is incorrect. You are passing the result of inet_addr(), cast to a pointer, but what you actually want is the address of this:

Host = gethostbyaddr(&addr, sizeof(addr), AF_INET);

(The other comments, that you should be using in_addr_t instead of unsigned long int are correct too, but it is unlikely that this specifically is causing your problem).


According to the documentation found here, you are passing in the wrong values:

gethostbyaddr() takes a struct in_addr or struct in6_addr and brings you up a corresponding host name (if there is one), so it's sort of the reverse of gethostbyname(). As for parameters, even though addr is a char*, you actually want to pass in a pointer to a struct in_addr. len should be sizeof(struct in_addr), and type should be AF_INET.

Here is some example code from the quoted site:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜