/*
 * Copyright(C) Paul und Scherer (mct.de/mct.net)
 *
 * This example demonstrates how to...
 *
 *  ... communicate with the ethernet
 *      module via telnet (port #23).
 */

#include <stdio.h>
#include "net.h"

#define SN	(255L<<24|255L<<16|255L<<8|192)	// choose subnet  mask
#define GW	(194L<<24| 64L<<16|159L<<8| 65)	//        gateway addr
#define IP	(194L<<24| 64L<<16|159L<<8| 79)	//        IP      addr
#define PN	23				//        port  number (telnet)

/*
 * The ethernet module channel 0 is initialized in TCP server mode.
 *
 * On connect, the program keeps listening for data which is simply
 * echoed (loopback).
 */
int
main(void)
{
	net_init(SN, GW, IP);			// initialize NET module

	printf("\n"
	       "NET2106 TCP server\n"
	       "==================\n\n"
	       "     Subnet mask : %3d.%3d.%3d.%3d\n"
	       " Gateway address : %3d.%3d.%3d.%3d\n"
	       "      IP address : %3d.%3d.%3d.%3d\n",
		net_rb(NET_SMR ), net_rb(NET_SMR +1), net_rb(NET_SMR +2), net_rb(NET_SMR +3),
		net_rb(NET_GAR ), net_rb(NET_GAR +1), net_rb(NET_GAR +2), net_rb(NET_GAR +3),
		net_rb(NET_SIPR), net_rb(NET_SIPR+1), net_rb(NET_SIPR+2), net_rb(NET_SIPR+3)
	);

	while (1) {
		static char buf[10000];		// r/w buffer

		int n;

		net_open(PN, 0);		// initialize socket (listen)

		printf("\nDisconnected, waiting for connection (port #%d)...\n", net_rw(NET_C0_SPR));

		while (net_rb(NET_C0_SSR) != NET_SE) ;	// wait for sock_established

		printf("Connected (%3d.%3d.%3d.%3d), received data is echoed...\n",
			net_rb(NET_C0_DIR  ),
			net_rb(NET_C0_DIR+1),
			net_rb(NET_C0_DIR+2),
			net_rb(NET_C0_DIR+3)
		);
		while ((n = net_read(buf, sizeof(buf)))) net_write(buf, n);
		net_close();
	}
}

