#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>


/*
 * lookuphost [ -d domain ] [ -n ] <address>
 * if domain specified, returns 0 for match, 1 for no match
 * keeps quiet if -n, else prints FQDN
 */


main(argc, argv)
int argc;
char **argv;
{
  struct hostent *host;
  struct in_addr in;
  extern char *optarg;
  extern int optind, opterr;
  int c;
  char *domain = NULL;
  int quiet = 0;
  int error = 0;

  while ((c = getopt(argc, argv, "d:n")) != -1) {
    switch (c) {
    case 'd':
      domain = optarg;
      break;
    case 'n':
      quiet = 1;
      break;
    default:
      error++;
      exit(1);
    }
  }

  if (error || optind >= argc) {
    if (!quiet)
      fprintf(stderr, "Usage: lookuphost [ -d domain ] [ -n ] <address>\n");
    exit(1);
  }

  in.s_addr = inet_addr(argv[optind]);	/* look up as an octet */

  host = gethostbyaddr((char *) &in, sizeof(in), AF_INET);
  if (host && host->h_name) {
    if (!quiet)
      printf("%s\n", host->h_name);

    if (domain) {
      int dlen = strlen(domain);
      int hlen = strlen(host->h_name);
      int d, h;

      if (dlen > hlen) exit(1);

      for (d = dlen-1, h = hlen-1; d >= 0; d--, h--) {
	if (domain[d] != host->h_name[h]) exit(1);
      }

      if (h >= 0) {
	if (host->h_name[h] != '.') exit(1);
      }
    }
    exit(0);
  }

  if (!quiet)
    fprintf(stderr, "No match for host %s.\n", argv[optind]);

  exit(1);
}
