Guest User

Untitled

a guest
Jan 22nd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.43 KB | None | 0 0
  1. #include <stdio.h>      // printf
  2. #include <stdlib.h>     // exit
  3. #include <arpa/inet.h>  // inet_ntop
  4. #include <netdb.h>      // gethostbyname
  5.  
  6. /*
  7.  
  8. It is a two-step process to connect to an Internet server when we are using a
  9. domain name, since domain names, though understood by humans, are not understood
  10. by the IP protocol through which Internet systems communicate:
  11.  
  12.   - First we must resolve the domain name to an IP address.
  13.   - Then we may use the IP address to correctly state the destination of our
  14.     data.
  15.  
  16. Here we focus on the domain name look-up, using gethostbyname().
  17.  
  18. */
  19.  
  20.  
  21. int main(int argc, char *argv[]) {
  22.  
  23.   if (argc != 2) {
  24.     printf("\n\nUSAGE: %s <hostname>\n\n", argv[0]);
  25.     exit(1);
  26.   }
  27.  
  28.   char* hostname = argv[1];
  29.   printf("Looking up the IP address of '%s'\n", hostname);
  30.  
  31.   // The hostent struct is used to describe domain name information returned
  32.   // from a look-up, which can include multiple addresses for the same domain
  33.   // name.
  34.   struct hostent *hostinfo;
  35.  
  36.   // Resolve the hostname to an IP address, ultimately via a DNS look-up.  For
  37.   // convenience, this will also accept addresses as strings (e.g.
  38.   // '72.21.210.250') and convert them to proper address structures, allowing
  39.   // users to specify either domain names or addresses in their applications.
  40.   hostinfo = gethostbyname(hostname);
  41.  
  42.   // Check if the look-up failed.
  43.   if (hostinfo == NULL) {
  44.     fprintf(stderr, "Unknown host %s.\n", hostname);
  45.     exit(1);
  46.   }
  47.  
  48.   // We are interested inthe h_addr attribute of the returned hostinfo, since
  49.   // this contains the first address.  Note that the OS networking services are
  50.   // generic, so gethostbyname could be used with many other protocols other
  51.   // than the now de facto IPv4, but here we are expecting a 4-byte IPv4 address
  52.   // so cast it appropriately to the in_addr (IPv4 address) structure.
  53.   struct in_addr *ip_address = (struct in_addr *) hostinfo->h_addr;
  54.  
  55.   // The IP address returned is simply 4 bytes, but often addresses are printed
  56.   // out in the dot notation (e.g. 72.21.210.250), so here we use the function
  57.   // inet_ntop to format our obtained address for display.
  58.   char ip_address_string[256];
  59.   // Flag AF_INET means: format the bytes in the Internet address family style.
  60.   inet_ntop(AF_INET, ip_address, (char *) &ip_address_string, sizeof(ip_address_string));
  61.   printf("'%s' -> %s\n", hostname, ip_address_string);
  62.  
  63.   return 0;
  64. }
Add Comment
Please, Sign In to add comment