/*
 * net.c
 *
 * This code was stolen from Andy Warner's original net.c (UNIX)
 * Very minor changes made it winsock2 compatible - 3.25.98 TPS
 *
 *
 * kgs is a server that sits between gdb and the KME interface to an
 * EPC host adapter.
 *
 * This file contains the network dependant code.
 */


#include <winsock2.h>
#include <io.h>

//#include "net.h"

/*
 * Open the required socket, and wait until someone connects
 * to it, working on the principle that the board can do what it likes
 * until there is a debugger ready to talk to it.
 *
 * Return the descriptor (>= 0) iff OK, -1 (with errno set) on error.
 */
int
OpenSocket(int port)
{
	int s, Temp ;
	struct sockaddr_in Local;
	struct protoent *Proto ;

	Proto = getprotobyname("tcp") ;
	if (!Proto) {
		return(-1) ;
	}

	/*
	 * Create the socket.
	 */
	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		//AfxMessageBox("Error: socket failed", (MB_OK));
		return(s) ;
	}

	/*
	 * Enable speedy re-use of this port.
	 */
	Temp = 1 ;
	setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char *)&Temp, sizeof(Temp)) ;

	/*
	 * Bind it to the port number specified.
	 */
	memset(&Local, 0, sizeof(Local)) ;
	Local.sin_family = AF_INET ;
	Local.sin_port = htons((WORD)port) ;
	Local.sin_addr.s_addr = htonl(INADDR_ANY) ;


	if (bind(s, (struct sockaddr *)(&Local), sizeof(Local)) == -1) {
		//AfxMessageBox("Error: bind failed", (MB_OK));
		_close(s) ;
		return(-1) ;
	}
	return(s);
}

void
CloseSocket(int s)
{
	shutdown(s, 2) ;
	_close(s) ;
}
