/*******************************************************************************
        udp_srv.c
        Z-World, 2000

        A UDP example, that receives the 'heartbeat' packets sent from
        udp_cli.c, and will receive either the direct-send packets or
        broadcast packets, depending on the configuration.
*******************************************************************************/

/***********************************
 * Configuration                   *
 * -------------                   *
 * All fields in this section must *
 * be altered to match your local  *
 * network settings.               *
 ***********************************/
/*
 * You must change the following values to whatever
 * your local IP address, netmask, and gateway
 * are. Contact your network administrator
 * for these numbers.
 */
#define MY_IP_ADDRESS   "10.10.6.101"
#define MY_NETMASK      "255.255.255.0"
#define MY_GATEWAY		"10.10.6.1"
#define MY_NAMESERVER	"10.10.6.1"

/*
 * Define the number of socket buffers that will be allocated for
 * UDP sockets.  We only need one UDP socket, so one socket buffer
 * will be enough.
 */
#define MAX_UDP_SOCKET_BUFFERS 1

/*
 * UDP demo configuration
 */
 
/* what local UDP port to use - we receive packets only sent to this port */
#define LOCAL_PORT	1234

/*
 * If this is set to "0", we will accept a connection from anybody.
 * The first person to connect to us will complete the socket with
 * their IP address and port number, and the local socket will be
 * limited to that host only.
 *
 * If it is set to all "255"s, we will receive all broadcast
 * packets instead.
 */
#define REMOTE_IP			"0"
//#define REMOTE_IP			"255.255.255.255" /*broadcast*/

/********************************
 * End of configuration section *
 ********************************/

#memmap xmem
#use "dcrtcp.lib"

udp_Socket sock;

/* receive one packet (heartbeat) */
int receive_packet(void)
{
	static char buf[128];

	#GLOBAL_INIT
	{
		memset(buf, 0, sizeof(buf));
	}

	/* receive the packet */
	if (-1 == udp_recv(&sock, buf, sizeof(buf))) {
		/* no packet read. return */
		return 0;
	}

	printf("Received-> %s\n",buf);
	return 1;
}

main()
{
	sock_init();
	/*printf("Opening UDP socket\n");*/
	
	if(!udp_open(&sock, LOCAL_PORT, resolve(REMOTE_IP), 0, NULL)) {
		printf("udp_open failed!\n");
		exit(0);
	}

	/* receive heartbeats */
	for(;;) {
		tcp_tick(NULL);
		receive_packet();
	}
}