#include "stdafx.h"
#include <xtl.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "kernel.h"
using namespace std;

#include "socket.h"

Socket::Socket()
{
	Connected = FALSE;
}

Socket::~Socket()
{
}

BOOL Socket::Connect(BYTE *IPAddr, WORD Port)
{
	DWORD dwResult; 
	XNetStartupParams xnsp; 
	XNADDR xna; 


	memset( &xnsp, 0, sizeof( xnsp ) ); 
	xnsp.cfgSizeOfStruct = sizeof( XNetStartupParams ); 
	xnsp.cfgFlags = XNET_STARTUP_BYPASS_SECURITY; 
	dwResult = XNetStartup( &xnsp ); 

	do 
	{ 
		dwResult = XNetGetTitleXnAddr( &xna ); 
	}
	while( dwResult == XNET_GET_XNADDR_PENDING ); 

	WORD wVersionRequested = MAKEWORD( 2, 2 ); 
	WSADATA wsaData; 

	dwResult = WSAStartup( wVersionRequested, &wsaData ); 

	// Create TCP/IP socket
    sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if( ( sock == SOCKET_ERROR ) || ( sock == INVALID_SOCKET ) )
    {
		return FALSE;
    }

	BOOL bBroadcast = TRUE;
	 
	if( setsockopt(sock, SOL_SOCKET, 0x5801, (PCSTR)&bBroadcast, sizeof(BOOL) ) != 0 )
	{
	}


    sockaddr_in httpServerAdd;

    httpServerAdd.sin_family = AF_INET;
    httpServerAdd.sin_port = htons( Port );
	httpServerAdd.sin_addr.S_un.S_un_b.s_b1 = IPAddr[0];
	httpServerAdd.sin_addr.S_un.S_un_b.s_b2 = IPAddr[1];
	httpServerAdd.sin_addr.S_un.S_un_b.s_b3 = IPAddr[2];
	httpServerAdd.sin_addr.S_un.S_un_b.s_b4 = IPAddr[3];                                                        

	if( connect( sock, ( struct sockaddr* )&httpServerAdd, sizeof( httpServerAdd ) ) == 0 )
    {
		
		Connected = TRUE;
		return 0;
	}
	else
	{
		return FALSE;
	}
}


BOOL Socket::Recieve(PBYTE pbData, DWORD dwSize)
{
	if (recv(sock, (char*)pbData, dwSize, NULL) == 0)
		return FALSE;

	return TRUE;
}

BOOL Socket::Send(PBYTE pbData, DWORD dwSize)
{
	if (send(sock, (char*)pbData, dwSize, NULL) == SOCKET_ERROR)
		return FALSE;

	return TRUE;
}

VOID Socket::Close()
{
	closesocket(sock);
	sock = NULL;
	Connected = FALSE;
}
