//udp server
// can work on unix or windows machines
// this program tests the time it takes to transfer a fixed file size by varying the packet size



#define WIN
//#define BSD

#ifdef WIN
	#include < windows.h>
#else
	#include < sys/types.h>    // Needed for system defined identifiers.
	#include < netinet/in.h>   // Needed for internet address structure.
	#include < sys/socket.h>   // Needed for socket(), bind(), etc...
	#include < arpa/inet.h>    // Needed for inet_ntoa()
	#include < fcntl.h>
	#include < netdb.h>
#endif


#include < stdio.h>	//printf
#include < iostream.h> //cout

//----- Defines ---------------------------------------------------------------
#define  PORT_NUM        1050      // Port number used
#define  MESS_SIZE			 10001



//the server loop
void dg_echo( int sockfd, struct sockaddr *pcliaddr, int clilen ) ;


int main( int argc, char **argv )
{
	int sockfd ;
	struct sockaddr_in servaddr, cliaddr ;
int status ;
	

#ifdef WIN
  WORD wVersionRequested = MAKEWORD(1,1);       // Stuff for WSA functions
  WSADATA wsaData;                              // Stuff for WSA functions
  
  // This stuff initializes winsock
  WSAStartup(wVersionRequested, &wsaData);
#endif

	
	
	
	sockfd = socket( AF_INET, SOCK_DGRAM, 0 ) ;


#ifdef WIN
	memset( (char *)&servaddr, 0, sizeof( servaddr ) ) ;
#else
	bzero( &servaddr, sizeof( servaddr ) ) ;
#endif
	
	
	servaddr.sin_family = AF_INET ;
	servaddr.sin_addr.s_addr = htonl( INADDR_ANY ) ;
	servaddr.sin_port = htons( PORT_NUM ) ;

	status = bind( sockfd, (struct sockaddr *) &servaddr, sizeof( servaddr ) ) ;

	dg_echo( sockfd, (struct sockaddr *) &cliaddr, sizeof( cliaddr ) ) ;




  // Close all open sockets (my socket)
#ifdef WIN
  closesocket( sockfd );
  WSACleanup();
#else
  close( sockfd );
#endif



	return 0 ;
}



void dg_echo( int sockfd, struct sockaddr *pcliaddr, int clilen )
{
	int n ;
	int len ;
	char mesg[ MESS_SIZE ] ;

	len = clilen ;
	printf( "waiting for udp packet\n" ) ;

	for( ; ; )
	{
cout << "before recv" << endl ;
		n = recvfrom( sockfd, mesg, MESS_SIZE, 0, pcliaddr, &len ) ;
cout << "after recv, before sendto" << endl;
		sendto( sockfd,	//in sendto, 28, ie 20 + 8, more bytes will be added
				  mesg,
				  n,
				  0,
				  pcliaddr,
				  len ) ;
cout << "after sendto" << endl;
	}
}