/*
 * connect.c
 *
 * client connection to hearts server
 */

#include <stdio.h>
#include "defs.h"
#include "local.h"

char *getenv();

/*
 * Make connection to host running the hearts distributor server,
 * return fd of new socket.
 */
connect_to(servhost, port)
char	*servhost;			/* name of host running server */
int	port;
{
	int	sock;
	struct	hostent *host;
	struct	servent *distributor;
	struct	sockaddr_in sockaddr;
	char	buf[64];

	if ((host = gethostbyname(servhost)) == NULL)  {
		perror("gethostbyname");
		exit(1);
	}
	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)  {
		perror("socket");
		exit(1);
	}
	bzero((char *) &sockaddr, sizeof (sockaddr));
	bcopy(host->h_addr, (char *) &sockaddr.sin_addr, host->h_length);
	sockaddr.sin_family = AF_INET;
	if (port)
		sockaddr.sin_port = htons(port);
	else {
		if ((distributor = getservbyname(SERVICE, PROTO)) == NULL)  {
			(void) sprintf(buf, "%s: service not found\n", SERVICE);
			fputs(buf, stderr);
			exit(1);
		}
		sockaddr.sin_port = distributor->s_port;
	}
	if (connect(sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr)) < 0) {
		(void) close (sock);
		return(0);
	}
	return(sock);
}
