/*
 *	Copyright 1988 by Rayan S. Zachariassen, all rights reserved.
 *	This will be free software, but only when it is finished.
 */

/*
 * Perhaps a single interface to discovering the real system name.
 */

#include "hostenv.h"
#include <stdio.h>
#if	defined(HAVE_RESOLVER)
#include <netdb.h>
#include <netinet/in.h>
#endif
#ifdef	HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif

int
getmyhostname(namebuf, len)
	char *namebuf;
	int len;
{
#if	defined(HAVE_RESOLVER)
	struct hostent *hp;
#endif	/* HAVE_RESOLVER */
#ifdef	HAVE_SYS_UTSNAME_H
	struct utsname id;
	extern int uname();

	if (uname(&id) < 0)
	  return -1;
	if (strlen(id.nodename) < len)
	  strcpy(namebuf, id.nodename);
#else	/* !HAVE_SYS_UTSNAME_H */
	extern int gethostname();
	
	if (gethostname(namebuf, len) < 0)
	  return -1;
#endif	/* USE_UNAME */
#if	defined(HAVE_RESOLVER)
	hp = gethostbyname(namebuf);
	if (hp != NULL) {
	  if (strlen(hp->h_name) < len)
	    strcpy(namebuf, hp->h_name);
	}
#if 0
	/* enable this code if for some reason your PTR name is primary */
	{
	  struct in_addr hpaddr;
	  if (hp != NULL)
	    memcpy(&hpaddr,hp->h_addr,hp->h_length);
	  if (hp != NULL
	      && (hp = gethostbyaddr((void*)&hpaddr, hp->h_length,
				     hp->h_addrtype)) != NULL) {
	    strcpy(namebuf,hp->h_name);
	  } else
	    return 0; /* Hmm.. Didn't quite knack it ? */
	}
#endif
#endif	/* HAVE_RESOLVER */
	return 0;
}
