Hi,
I am currently looking through a simple C program which basically is a very basic nslookup tool. My question is regarding on how some of the C code in this is working.
Here is the pieces of code:
Code:
/* Bare nslookup utility (w/ minimal error checking) */
#include <stdio.h> /* stderr, stdout */
#include <netdb.h> /* hostent struct, gethostbyname() */
#include <arpa/inet.h> /* inet_ntoa() to format IP address */
#include <netinet/in.h> /* in_addr structure */
int main(int argc, char **argv) {
struct hostent *host; /* host information */
struct in_addr h_addr; /* internet address */
if (argc != 2) {
fprintf(stderr, "USAGE: nslookup <inet_address>\n");
exit(1);
}
if ((host = gethostbyname(argv[1])) == NULL) {
fprintf(stderr, "(mini) nslookup failed on '%s'\n", argv[1]);
exit(1);
}
h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
fprintf(stdout, "%s\n", inet_ntoa(h_addr));
exit(0);
}
The in_addr structure looks like this:
Code:
struct in_addr {
__u32 s_addr;
};
I would like to know how does the following line of the code works and if someone could break it down how to read this line:
Code:
h_addr.s_addr = *((unsigned long *) host->h_addr_list[0]);
The code defines the following structure: struct hostent *host;
Which looks like this:
Code:
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. */
};
Here is the function prototype for gethostbyname function:
Code:
/* Return entry from host data base for host with NAME.
This function is a possible cancellation point and therefore not
marked with __THROW. */
extern struct hostent *gethostbyname (__const char *__name);
If i understand it correctly this function returns a point to structure hostent. Is this correct and all the values are populated in the hostent structure shown above.
What does is type is __u32 this is in struct in_addr?
So the argv[1] is passed to gethostbyname() funtion which returns a pointer to structure and the address is stored in the h_addr_list[0] and this assigned to h_addr and this is passed to net_ntoa(h_addr) to print the output in correct format. Is this correct understanding?
Thanks