×
Namespaces

Variants
Actions

How to get network host entry

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: polaka_sr (16 Jun 2008)
Last edited: hamishwillee (08 Feb 2012)

The gethostbyname, and gethostbyaddr functions each return a pointer to an object with the following structure describing an internet host referenced by name or by address, respectively.

The name argument passed to gethostbyname should point to a NUL -terminated hostname. The addr argument passed to gethostbyaddr should point to an address which is len bytes long, in binary form (i.e., not an IP address in human readable ASCII form). The type argument specifies the address family (e.g. AF_INET, etc.) of this address.

The structure returned contains either the information obtained from the name server,

struct  hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses from name server */
};
#define h_addr h_addr_list[0] /* address, for backward compatibility */

When using the nameserver, gethostbyname will search for the named host in the current domain and its parents unless the name ends in a dot.


Following is the snippet which tells the usage of gethostbyname:

#include<stdio.h>
#include<arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
Int main()
{
struct hostent *hp = 0;
char *test_url=www.google.com:
hp = gethostbyname(test_url);
if(hp==NULL)
printf(“gethostbyname failed”):
else
printf(“gethostbyname passed”);
return 0;
}

Following is the snippet which tells the usage of gethostbyaddr:

#include<stdio.h>
#include<arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#define urlsize 50
Int main()
{
struct hostent *hp = 0;
char addr[256];
unsigned long test_addr;
strcpy(addr,” 147.243.3.83”);
test_addr=inet_addr(addr);
struct hostent *hp;
hp=gethostbyaddr((const char *)&test_addr,sizeof(test_addr),AF_INET);
if(hp)
printf(“DNS query resolved”);
else
printf(“gethostbyaddr failed”);
return 0;
}


Error return status from gethostbyname and gethostbyaddr is indicated by return of a NULL pointer.


Wiki Links

Generic functions for system database functions

This page was last modified on 8 February 2012, at 05:32.
42 page views in the last 30 days.
×