/*************************************************************************************************************
* This file create a connection with server
* 2012/6 by Dlxko
**************************************************************************************************************/
#include "Connect.h"

// Handler
static SOCKET s;
static int	err_h;

// For WinSock version and data
static WSADATA wsaData;

//Socket address information
static SOCKADDR_IN target;

// Reciving variables
static int result = 10;

/**** CONNECT ****/
SOCKET dxconnect()
{
	/* Start WinSock or report error */
	err_h = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
	if ( err_h != 0 )
	{
		memset(dialog_text, 0, 100);
		sprintf_s(dialog_text, 100, "WinSock start error %ld \n", WSAGetLastError() );
		function_show_error(dialog_text);
	}

	/* Build address structure to bind to socket */
	target.sin_family = AF_INET; // address family Internet
	target.sin_port = htons (port); //Port to connect on
	target.sin_addr.s_addr = inet_addr (ip_addres); //Target IP

	/* Create SOCKET */
	s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s == INVALID_SOCKET)
	{
		memset(dialog_text, 0, 100);
		sprintf_s(dialog_text, 100, "Socket error %ld \n" , WSAGetLastError() );
		function_show_error(dialog_text);
	}

	/* Try connect to server */
	if(connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
	{
		memset(dialog_text, 0, 100);
		sprintf_s(dialog_text, 100, "Connect error %ld \n", WSAGetLastError() );
		function_show_error(dialog_text);
	}

	// Return socket
	return s;
}