views:

117

answers:

3

I am not getting this assignment about finding the IP address of the machine. I need help understanding the logic of this code. Our college lab uses proxy server; will this code work on a computer without proxy?

      #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);
      }
+2  A: 

The 2 key methods of interest here are:

  1. gethostbyname() - The gethostbyname function retrieves host information
  2. inet_ntoa - convert ip add to in_addr

Try to be specific, where are you having problem understanding the code.

The code works with me.

$./a.out nslookup

returns host ip.

zengr
+1 for linking Beej.
Thom Smith
Not getting the pointer variable *host and condition to be tested in if()
Ahsan
A: 

Actually, the gethostbyname function performs a DNS request which returns the hostent structure filed. It could be interesting for you to snif the network with wireshark for instance to look what the traffic looks like.

Aif
+1  A: 

netdb.h - definitions for network database operations arpa/inet.h - definitions for internet operations netinet/in.h - Internet address family The gethostname() function returns the standard host name for the current machine. inet_ntoa(h_addr) To convert an IP address from 32-bit network format back to dotted decimal.

These are the basic understanding terms. Most importantly use google for detail.

Tauquir