DriverBoy
DriverBoy

Reputation: 997

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?

Upvotes: 0

Views: 1409

Answers (3)

caf
caf

Reputation: 239321

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).

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70344

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

Upvotes: 0

user2100815
user2100815

Reputation:

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.

Upvotes: 1

Related Questions