问题描述:

Code follows:

struct sockaddr_in ipv4addr;

ipv4addr.sin_addr.s_addr = inet_addr("127.0.0.1");

struct hostent *he;

he = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);

if(he)

printf("Host name: %s\n", he->h_name);

else

printf("Error AHAHA:%s\n", strerror(errno));

But it clearly says that

Return Value

The gethostbyname() and gethostbyaddr() functions return the hostent

structure or a NULL pointer if an error occurs. On error, the h_errno

variable holds an error number. When non-NULL, the return value may

point at static data, see the notes below.

This piece of code result in printing Error AHAHA:SUCCESS, and this also means that it run into else, which indicates he is NULL which shouldn't be.

UPDATE:

memset(&ipv4addr,0,sizeof(ipv4addr));

ipv4addr.sin_family = AF_INET;

adding these I somehow got the hostname of

ANantes-651-1-49-net.w2-0.abo.wanadoo.fr(2.0.0.0)???

网友答案:

As others have stated in comments, the gethostby...() functions assign the error code to h_errno rather than to errno. They are not the same thing! You can also use gethostbyaddr_r() to get the error code. But either way, use hstrerror() instead of strerror() to report the error message.

You are also not populating the sockaddr_in.sin_family field. That is why the code works with using inet_pton(). Even though gethostbyaddr() takes a family as an input parameter, you still have to pass it a correctly populated sockaddr_in so it can validate that you really are passing in an IPv4 address and not another address type, like IPv6.

Try this:

struct sockaddr_in ipv4addr;
memset(&ipv4addr, 0, sizeof(ipv4addr));
ipv4addr.sin_family = AF_INET;
ipv4addr.sin_addr.s_addr = inet_addr("127.0.0.1");
struct hostent *he = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);
if(he)
    printf("Host name: %s\n", he->h_name);
else
    printf("Error AHAHA:%s\n", hstrerror(h_errno));
网友答案:

I still don't know why I'm getting other host names, but this worked for me

char ipv4addr[sizeof(struct in_addr)];
inet_pton(AF_INET, "127.0.0.1", ipv4addr);  
struct hostent *he;
he = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);
if(he)
    printf("Host name: %s\n", he->h_name);
else
    printf("Error AHAHA:%s\n", hstrerror(h_errno));

And yes,I changed strerror(errno) to hstrerror(h_errno)

相关阅读:
Top