/*
UDP01.c: Responds to the message received from a UDP client.
         Listen port is 10000
          
Compiler: BC++ 3.1, 
          Turbo C++ 1.01(3.01) (free from http://cc.codegear.com/free/cpp)
          MSC 6.0,
          MSVC 1.52.
      
Compile mode: large

Project: UDP01.c 
         ..\..\lib\7186el.Lib
         ..\..\lib\tcp_dm32.lib 

Hardware: uPAC-7186EX series
    
[Nov 03, 2008] by Liam
*/

#include "..\..\lib\7186e.h"
#include "..\..\lib\Tcpip32.h"

uchar InBuf[1500], OutBuf[1500];
struct ip host_ip;

void main(int argc, char *argv[])
{   
    int skt;
    int err, quit=0;
    int DataBytes;
  
    InitLib();
  
    GetSavedIp(&host_ip);
    lhip("7186EX", &host_ip);
    Print("IP=%d.%d.%d.%d Mask=%d.%d.%d.%d\r\n", host_ip.addr.c[0], host_ip.addr.c[1],
                                                 host_ip.addr.c[2], host_ip.addr.c[3],
                                                 host_ip.mask.c[0], host_ip.mask.c[1],
                                                 host_ip.mask.c[2], host_ip.mask.c[3]);
                                                 
    err=Ninit();    // initiate host environment
    if(err<0)
    {
        Print("Ninit() failed!");
        
        return;
    }
    
    err=Portinit("*");  // initiate network device
    if(err<0)
    {
        Print("Portinit() failed!");
        Nterm();
        
        return;
    }

    skt=Nopen("*", "UDP/IP", 10000, 0, S_NOCON | S_NOWA);
    if(skt<0)
    {
        Print("Cannot open a connection for UDP/IP!");
        Nterm();
        
        return;
    }  
  
    Print("Socket=%d\r\n", skt);
    SOCKET_NOBLOCK(skt);
  
    while(!quit)
    {
        YIELD();    // must add this line in the while loop
        
        DataBytes=Nread(skt, InBuf, 1500);
        if(DataBytes>0)
        {
            memcpy(OutBuf, InBuf, DataBytes);
            Nwrite(skt, OutBuf, DataBytes);
        }

        if(Kbhit())
        {
            switch(Getch())
            {
                case 'q':
                case 'Q':
                    quit=1;
                    break;
            }
        }
    }

    Nclose(skt);
    Nterm();
}