*
 * Program Name:  echoserver.c
 * runs on CTOS and UNIX, can be used to test the terminal examples
 *
	 
include <systypes.h>
include syssocket.h
include netinetin.h
	*	include <arpainet.h> *
include netdb.h
*include stdio.h*
	*	include <sysioctl.h> *
	
ifdef CTOS
define send ssend
endif

define ECHOPORT    3000	 
define RECBUFFSZ   2000	 

extern int errno;       * global error code returned from system calls *
int Trace=0;            * if TRUE will trace good returns with the bad *

main ()
{
int S;                  * file descriptor returned by socket call      *
int N;                  * variable used as a return value of calls     *
int Ns;                 * accepted socket file descriptor              *
char Buf[RECBUFFSZ];    * data recvd is stored here                  *
struct sockaddr_in Server, Client; * local and remote host addresses   *
int IdataLen;           * number of characters received                *
int ClientAddrLen;      * Client Address Length                        *

	printf(Echoserver initializing...\n);

	S = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
	CheckP (S , socket);
	printf(Socket assigned.\n);

	Server.sin_family = AF_INET;            * assign server attributes *
	Server.sin_port =  htons(ECHOPORT);
	Server.sin_addr.s_addr = htonl(INADDR_ANY);
	N = bind (S, Server, sizeof (Server));
	CheckP (N , bind );
	
	N = listen (S, 1);
	CheckP (N , listen);
	printf(Listen successful.\n);
	 
	Client.sin_family = AF_INET;            * assign domain            *
	Client.sin_addr.s_addr = htonl(INADDR_ANY);    * accept any valid address *
	Client.sin_port = htons(0);                    * accept any valid port    *
	ClientAddrLen = sizeof (Client);
	 
	printf(Echoserver ready.\n);

	for (;;) {
	    Ns = accept (S, Client, ClientAddrLen);  * accepts a connection *
	    CheckP (Ns, accept);
	    printf(\nAccept successful. Receiving: );
	 
	    while ( (IdataLen = recv (Ns, Buf, sizeof (Buf), 0))>0){
	        N= send(Ns, Buf, IdataLen, 0);
	        printf ( d, IdataLen);
	    }
*	    printf (\n recv errno=d ... closing connection\n, errno);
	    printf (CTOSerrno is: d\n,CTOSerrno); *	    
	    close (Ns);
	} 
}

CheckP (n, msg)
**************
 * check n positive else display msg  quit
 *
int n;
char *msg;
{
	if (n<0){
		printf ( Program terminated: error u in s\n, errno, msg);
		exit (1);
	} else {
		if (Trace) printf (Trace OK: s\n, msg);
	}
} 

