/* BNAS Client - Copyright (C) 1998 Bernardo Innocenti
 * vi:ts=4
 *
 * This is a simple program that I use to forward an audio
 * stream through the TCP/IP LAN from my Sun SparcStation to my Amiga.
 */

#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define AUDIOPORT	6581	/* default audio port */
#define BUFSIZE		32768	/* Audio buffer size */


int open_sock(int sock, char *server, int port)
{
	struct sockaddr_in blah;
	struct hostent *he;

	memset ((char *)&blah, sizeof(blah), 0);
	blah.sin_family=AF_INET;
	blah.sin_addr.s_addr=inet_addr(server);
	blah.sin_port=htons(port);

	if ((he = gethostbyname (server)) != NULL) 
		memcpy ((char *)&blah.sin_addr, he->h_addr, he->h_length);
	else
		if ((blah.sin_addr.s_addr = inet_addr(server)) < 0)
		{
			perror("gethostbyname()");
			return(-3);
		}

	if (connect(sock,(struct sockaddr *)&blah,16)==-1)
	{
		perror("connect()");
		close(sock);
		return(-4);
	}
	printf("Connected to [%s:%d].\n", server, port);
	return 0;
}


int main (int argc, char *argv[])
{
	int s;
	int audiofile;
	int connected;
	size_t size;
	char buf[BUFSIZE];

	if (argc != 2)
	{
		printf("Usage: %s <server>\n", argv[0]);
		return 0;
	}
	if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
	{
		perror ("socket()");
		return -1;
	}

	if (!open_sock (s, argv[1], AUDIOPORT))
	{
		connected = 1;
		while (connected && ((audiofile = open ("/dev/audio", O_RDONLY)) >= 0))
		{
			while (connected && ((size = read (audiofile, buf, BUFSIZE)) > 0))
			{
				if (send (s, buf, size, 0) == -1)
				{
					perror ("audioclient: ");
					connected = 0;
				}
			}
			close (audiofile);
		}

		close (s);
	}

	return 0;
}
