#include "precomp.h"
#include "udppeer.h"

/* Get the IP address associated with the hostname passed to the constructor. */
UDPClient::UDPClient(char *RemoteAddress)
{
	WSADATA	wsaData;
	
	if (WSAStartup(MAKEWORD(2,1),&wsaData))	{	return;	}

	UDPSocket = (UINT) socket (AF_INET,SOCK_DGRAM, 0);
	// Fill in the local socket address information
	LocalAddr.sin_family	= AF_INET;            // Address family to use
	LocalAddr.sin_port		= htons(REMOTE_PORT);    // Port number to use
	
	unsigned long RemoteIP = inet_addr(RemoteAddress);
	if(RemoteIP == INADDR_NONE)	{	/*error*/ }
	LocalAddr.sin_addr.s_addr = RemoteIP;
}

UDPClient::UDPClient(unsigned long RemoteIP)
{
	WSADATA	wsaData;
	
	if (WSAStartup(MAKEWORD(2,1),&wsaData))	{	return;	}

	UDPSocket = (UINT) socket (AF_INET,SOCK_DGRAM, 0);
	// Fill in the local socket address information
	LocalAddr.sin_family	= AF_INET;            // Address family to use
	LocalAddr.sin_port		= htons(REMOTE_PORT);    // Port number to use
	
	if(RemoteIP == INADDR_NONE)	{	/*error*/ }
	LocalAddr.sin_addr.s_addr = RemoteIP;
}


UDPClient::~UDPClient()
{
	closesocket(UDPSocket);
	WSACleanup();
}

/*	Send some data	*/
int UDPClient::TransmitData(char *buffer)
{
	sendto(UDPSocket, buffer, sizeof(DATAGRAM), 0, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr));
	return 1;
}

SOCKADDR_IN UDPClient::GetAddr()
{
	return LocalAddr;
}

/*	Bind the server socket so it will listen for datagrams from any IP address.
	WSAAsyncSelect is called for asynchronous notification of the main
	window procedure when a datagram is received.
*/
UDPServer::UDPServer(HWND hWnd)
{
	WSADATA	wsaData;
	
	if (WSAStartup(MAKEWORD(2,1),&wsaData))	{	return;	}

	UDPSocket = (UINT) socket (AF_INET,SOCK_DGRAM, 0);
	
	// Fill in the local socket address information
	LocalAddr.sin_family	= AF_INET;            // Address family to use
	LocalAddr.sin_port		= htons(LOCAL_PORT);    // Port number to use
	
	LocalAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(UDPSocket, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr));
	WSAAsyncSelect(UDPSocket, hWnd, WM_SOCKETREAD, FD_READ);
}

UDPServer::~UDPServer()
{
	closesocket(UDPSocket);
	WSACleanup();
}

/*	Receive a datagram */
int UDPServer::ReceiveData(char *buffer)
{
	// Wait to receive a message from client
	int AddrLength = sizeof(SOCKADDR_IN);
	recvfrom(UDPSocket, buffer, sizeof(DATAGRAM), 0, (struct sockaddr *)&RemoteAddr, &AddrLength);
	// RemoteAddr stores the remote address from which the datagram was received.

	return 1;
}

SOCKADDR_IN UDPServer::GetRemoteAddr()
{
	return RemoteAddr;
}