/*
host2ip.c - return IP address given a host name

Copyright 1998-1999 by Columbia University; all rights reserved 
*/

#include <sys/types.h>
#include <sys/socket.h>      /* struct sockaddr */
#include <stdlib.h>
#include <netdb.h>           /* gethostbyname() */
#include <netinet/in.h>      /* sockaddr_in */
#include <arpa/inet.h>       /* inet_addr() */
#include <rpcsvc/ypclnt.h>   /* YP */
#include <ctype.h>           /* isspace() */
#include <string.h>          /* strlen() */
#include "sysdep.h"          /* For NT compatibility */

static char rcsid[]  = "$Id: host2ip.c,v 1.15 2000/04/06 04:08:57 lennox Exp $";
/*
* Return IP address given host name 'host'. Returns INADDR_ANY if not valid.
* This function is ALMOST thread-safe Except for yp_get_default_domain()
* NOTE: always include the correct function prototype,
*    extern int host2ip(char *host);
* is not correct and will cause memory problems.
*/
struct in_addr host2ip(char *host)
{
  struct in_addr in, tmp;
  struct hostent *hep;
  struct hostent host_e;

  /* Strip leading white space. */
  if (host) {
    while (*host && isspace((int)*host)) host++;  
  }

  /* Check whether this is a dotted decimal. */
  in.s_addr = INADDR_ANY;
  if (!host) {
  }
  else if ((tmp.s_addr = inet_addr(host)) != -1) {
    in = tmp;
  }
  /* Attempt to resolve host name via DNS. */
  else {
#ifdef GETHOSTBYNAME_R_RETVAL_AS_PTR
    /* Linux has a weird gethostbyname_r. */

    char databuf[1024]; /* 256 bytes temp storage for host_e */
    int hh_errno; /* per thread errno for gethostbyname_r */

    gethostbyname_r(host, &host_e, databuf, sizeof(databuf),
			    &hep, &hh_errno);
    if (hep != NULL) {
      in = *(struct in_addr *)(hep->h_addr_list[0]);
    }

#elif GETHOSTBYNAME_R_OSF1_DEPRECATED
    /* OSF/1 has a weirder gethostbyname_r. */
    struct hostent_data host_d;
    memset(&host_d, 0, sizeof(host_d));
    if (gethostbyname_r(host, &host_e, &host_d) == 0) {
      hep = &host_e;
      in = *(struct in_addr *)(hep->h_addr_list[0]);
    }

#else
    /* "Normal" (Solaris) gethostbyname_r */
    char databuf[1024]; /* 256 bytes temp storage for host_e */
    int hh_errno; /* per thread errno for gethostbyname_r */
     if ((hep = gethostbyname_r(host, &host_e, databuf, sizeof(databuf),
                                &hh_errno)) != NULL) {
      in = *(struct in_addr *)(hep->h_addr_list[0]);
    }
#endif
    /* else if ((hep = gethostbyname(host))) {  */
     else {
       /* As a last resort, try YP. */
       static char *domain = 0;  /* YP domain */
       char *value;              /* key value */
       int value_len;            /* length of returned value */
       
       if (!domain) yp_get_default_domain(&domain);
       if (yp_match(domain, "hosts.byname", host, strlen(host), &value,
                    &value_len) == 0) {
         in.s_addr = inet_addr(value);
       }
     }
  }
  return in;
} /* host2ip */
