Google

gethostbyaddr

ipaddress to hostname without a single shred of error checking. This code will take an ipaddress as an argument and return the hostname associated with it using gethostbyaddr. It should have more error checking and a lot of other stuff, but this is just to show the base code. Cut and paste away. #include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>

int main(int argc, char **argv) {
    struct hostent *hostname = malloc(sizeof(struct hostent));
    extern int h_errno;

    struct in_addr *ipaddr = malloc(sizeof(struct in_addr));
    ipaddr->s_addr=inet_addr(argv[1]) ;
    if ( (hostname = gethostbyaddr((char *) ipaddr,sizeof(ipaddr),AF_INET)) == NULL ) {
        printf ("%s\n","unknown");
        exit(1);
    }
    printf ("%s\n",hostname -> h_name);
}

One Response to “gethostbyaddr”

  1. Carl Jolly Says:

    Mallocing memory for the hostname is unnecessary and will result in a memory leak if someone converts this into a function. The call gethostbyaddr returns a pointer to a static hostent structure that will be overwritten by subsequent calls. Setting hostname equal to the return value of gethostbyaddr will modifiy the value of hostname to point away from the memory you allocated; thus you get a memory leak. Use memcpy to save the contents of the return value to the local struct if required.

Leave a Reply