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

int net(progname, uid, version)
     char *progname;
     int uid;
     char *version;
{
  static char *host;		/* name of host running cview daemon. */
  static char **serv;		/* cview service hesiod info. */
  static struct hostent *hp;	/* hostent struct for cview server. */
  static struct servent *sp;	/* servent struct for cview service. */
  static struct sockaddr_in sin; /* Socket address. */
  static int init = 0;		/* Have we been here before? */
  int s;			/* Socket to connect to cview daemon. */
  char buf[BUFSIZ];		/* Temporary buffer. */

  if (!init)
    {
      host = "bad-loud-music.mit.edu";
#ifdef notdef
      serv = hes_resolve("cview","sloc"); 

      if (serv == NULL)
	host = "doghouse.mit.edu";	/* fall back if hesiod is broken... */
      else
	host = *serv;
#endif

      hp = gethostbyname(host);

      if (hp == NULL) 
	{
	  fprintf(stderr, "%s: Unable to resolve hostname '%s'.\n",
		  progname, host);
	  return(-1);
	}
  
#ifdef notdef
      sp = getservbyname("cview", "tcp");
      if (sp == 0) 
	{
	  fprintf(stderr, "%s: Unknown service 'tcp/cview'.\n", progname);
	  return(-1);
	}
#endif

      memset(&sin, 0, sizeof (sin));
      memmove((char *)&sin.sin_addr, hp->h_addr, hp->h_length);
      sin.sin_family = hp->h_addrtype;
      sin.sin_port = 13031 /*sp->s_port*/;

      init = 1;
    }
  
  s = socket(hp->h_addrtype, SOCK_STREAM, 0);
  if (s < 0) 
    {
      perror("socket"); 
      return(-1);
    }

  if (connect(s, &sin, sizeof (sin)) < 0) 
    {
      perror("connect");
      close(s);
      return(-1);
    }

  sprintf(buf, "%d %s\n", uid, version);
  if (write(s, buf, strlen(buf)) == -1)
    {
      perror("write");
      close(s);
      return(-1);
    }

  return(s);
}
