home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / unix / programm / 5677 < prev    next >
Encoding:
Text File  |  1992-12-14  |  2.1 KB  |  81 lines

  1. Newsgroups: comp.unix.programmer
  2. Path: sparky!uunet!gatech!concert!mercury!muquit
  3. From: muquit@mercury.ncat.edu
  4. Subject: Re: Get hostname from IP address
  5. Message-ID: <1992Dec14.042053.7413@mercury.ncat.edu>
  6. Organization: North Carolina A&T State University
  7. Date: Mon, 14 Dec 1992 04:20:53 GMT
  8. Lines: 71
  9.  
  10. And this one also can get IP address from hostname.
  11. I just took some code out from 'ncftp'. The first part was
  12. posted by someone else few days back. 
  13. So, credit goes to the authors.
  14.  
  15. -------------------CUT--------------
  16. /*  Get host name from IP address
  17.  *  Get IP address from host name
  18.  */
  19.  
  20. #include <stdio.h>
  21. #include <sys/types.h>
  22. #include <sys/socket.h>
  23. #include <netdb.h>
  24. #include <netinet/in.h>
  25. #include <arpa/inet.h>
  26.  
  27. main (argc, argv)
  28. int argc;
  29. char **argv;
  30. {
  31.    char *add;
  32.    unsigned long addr_bin;
  33.    unsigned long horder;
  34.    struct hostent *host;
  35.    char *name;
  36.    int j;
  37.  
  38.    if (argc<2) { 
  39.       fprintf(stderr,"Usage:\n%s Site Name\n%s IP Number\n",argv[0],argv[0]);
  40.       exit();
  41.    }
  42.    add= argv[1];
  43.   if ( (sscanf(argv[1],"%d.%d.%d.%d",&j,&j,&j,&j)) == 4){
  44. fprintf(stderr,"\nTrying to get Host Name...\n\n");
  45. if ((inet_addr (argv[1])) == 0xffffffff) {
  46. (void) fprintf(stderr, "This IP adress MUST NOT be valid.. :-)\n\n");
  47. exit(1);
  48.             }
  49.    addr_bin= inet_addr(add);
  50.    host= gethostbyaddr((char*) &addr_bin, sizeof(addr_bin),AF_INET);
  51. if (host == NULL) {
  52. if (h_errno == HOST_NOT_FOUND) {
  53. (void) printf("Sorry! Can't find any Host Name with IP Address \"%s\"\n\n", argv[1]);
  54.    exit(1);
  55.    }
  56.    }
  57.    name=host->h_name;
  58.    printf("Host Name is : %s\nIP address   : %s\n\n",name,add);
  59. exit(0);
  60. }
  61. /***************/
  62. fprintf(stderr,"\nTrying to get IP Address...\n\n");
  63. host=gethostbyname(argv[1]);
  64. if (host == NULL) {
  65. if (h_errno == HOST_NOT_FOUND) {
  66. (void) printf("Sorry! Can't find any Host by the name \"%s\"\n\n", argv[1]);
  67. exit(1);
  68. }
  69. }
  70. if(*host->h_addr_list){
  71. horder=ntohl(*(unsigned long *) *(char **) host->h_addr_list);
  72. printf("IP Address is : %lu.%lu.%lu.%lu\n",
  73. (horder >> 24),
  74. (horder >> 16) & 0xff,
  75. (horder >> 8 ) & 0xff,
  76. horder & 0xff);
  77. fprintf(stderr,"Host name is  : %s\n\n",add);
  78.    }
  79.    }
  80.  
  81.