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

// Local statics
static int	err_h;
static WSADATA wsaData;
static SOCKADDR_IN target;
static int result = 10;

// Connect to server
SOCKET dxconnect()
{
	// Start WinSock or report error
	err_h = WSAStartup( MAKEWORD( 2, 2 ), &wsaData );
	if ( err_h != 0 )
	{
		memset(dialog_text, 0, DIALOG_BUFFER_SIZE);
		sprintf_s(dialog_text, DIALOG_BUFFER_SIZE, "%s : %d", LANG_WINSOCK_START_ERROR, 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 or report
	s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (s == INVALID_SOCKET)
	{
		memset(dialog_text, 0, DIALOG_BUFFER_SIZE);
		sprintf_s(dialog_text, DIALOG_BUFFER_SIZE, "%s : %d", LANG_WINSOCK_SOCKET_ERROR, WSAGetLastError());
		function_show_error(dialog_text);
	}

	// Try connect to server
	if(connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
	{
		memset(dialog_text, 0, DIALOG_BUFFER_SIZE);
		sprintf_s(dialog_text, DIALOG_BUFFER_SIZE, "%s : %d", LANG_WINSOCK_CONNECT_ERROR, WSAGetLastError());
		function_show_error(dialog_text);
	}

	// Return socket
	return s;
}