You are passing the wrong struct into gethostbyaddr. You were passing a
sockaddr_in when you need to pass a
in_addr struct. Take a look at the following exampe program:
Code:
#include <netdb.h>
#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
main( int argc, char *argv[])
{
struct in_addr addr;
struct hostent *hp;
char *ptrError = NULL;
if ( argc != 2 )
{
printf("Usage: %s ip_address\n\n", argv[0]);
exit(0);
}
addr.s_addr = inet_addr( argv[1] );
if (addr.s_addr == -1)
{
printf("Bad address\n\n");
exit(-1);
}
hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
if (!hp)
{
printf("[%d] %s\n", errno, strerror( errno ) );
herror( ptrError );
printf( "%s\n", ptrError );
exit(-1);
}
else
printf( "Hostname: %s\n\n", hp->h_name);
}
A simple change to your program would make it work:
Code:
main()
{
struct sockaddr_in sad;
struct hostent *p;
sad.sin_addr.s_addr = inet_addr( "198.186.203.77" );
p = gethostbyaddr((char *)&(sad.sin_addr),sizeof(sad.sin_addr),AF_INET);
printf("%u",p); //here i get a null always! thats the problem!!!
}
Notice that I pass in &sad.sin_addr into gethostbyaddr.