#include <netdb.h>
#define MAX_STRING_SIZE 256

int dqs_getdomainname(domain_name,max_size)
char *domain_name;
int  max_size;

{

int  i;
char *ptr;
char host_name[MAX_STRING_SIZE];
char qhost_name[MAX_STRING_SIZE];
struct hostent *hent;

  sprintf(domain_name,"%s","UNKNOWN");

  if (gethostname(host_name,MAX_STRING_SIZE))
    {
      perror("gethostname() failure");
      return(-1);
    }

  if (getdomainname(domain_name,max_size))
    {
      perror("getdomainname() failure");
      sprintf(domain_name,"%s","UNKNOWN");
    }

  if ((strlen(domain_name)==0)||(!strcmp(domain_name,"(none)")||(!strcmp(domain_name,"UNKNOWN"))))
    {
      perror("getdomainname() returned crap");
      printf("trying to derive domain from hostname\n");
      hent=gethostbyname(host_name);
      if (!hent)
	{
	  perror("gethostbyname() failure - gotta punt at this point...");
	  return(-1);
	 }

      sprintf(qhost_name,"%s","UNKNOWN");

      if (strstr(hent->h_name,".")) /* cool, a qualified hostname */
	sprintf(qhost_name,"%s",hent->h_name);
      else
	{
	  if (hent->h_aliases)
	    for(i=0;hent->h_aliases[i];i++)
	      {
		printf("h_aliases--->%s<\n",hent->h_aliases);
		if (strstr(hent->h_aliases,"."))
		sprintf(qhost_name,"%s",hent->h_name);
	      }
	}
      printf("qualified host name --->%s<---\n",qhost_name);
      ptr=(char *)index(qhost_name,'.');
      if (!ptr)
	return(-1);
      else
	{
	  sprintf(domain_name,"%s",++ptr);
	  return(0);
	}
    }
  else
    {
      sprintf(domain_name,"%s",domain_name);
      return(0);
    }

  sprintf(domain_name,"%s","UNKNOWN");
  return(-1);

}

/*********************************************************
mmain(argc, argv,envp)
int argc;
char **argv;
char **envp;

{



char domain_name[MAX_STRING_SIZE];

       if (dqs_getdomainname(domain_name,MAX_STRING_SIZE))
	 {
              perror("dqs_getdomainname() failure");
              exit(-1);
	 }
printf(">%s<\n",domain_name);

}

*/
