Example #1
0
bool TCPSocket::Connect( const IPv4Address& destination )
{
	//Set up the socket
	m_Socket = static_cast< int >( socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ) );	// Adress Family = INET and the protocol to be used is TCP
	if ( m_Socket <= 0 )
	{
		LogErrorMessage( "Failed to create socket", "TCPSocket" );
		return false;
	}

	SetBlockingMode( false );

	// Try to connect
	Logger::Log( "Attempting to connect to " + destination.GetPrintableAddressAndPort(), "TCPSocket", LogSeverity::INFO_MSG );
	sockaddr_in addr = destination.GetSockAddr();

	timeval timeOut;
	timeOut.tv_sec = CONNECTION_TIMEOUT_SECONDS;
	timeOut.tv_usec = 0;

	fd_set set;
	FD_ZERO( &set );
	FD_SET( m_Socket, &set );

	int returnVal;
	if ( ( returnVal = connect( m_Socket, ( sockaddr * )&addr, sizeof( sockaddr_in ) ) ) == INVALID_SOCKET )
	{
		if ( !SHOULD_WAIT_FOR_TIMEOUT )
			return false;
	}
	returnVal = select( static_cast<int>( m_Socket + 1 ), NULL, &set, NULL, &timeOut );

	if ( returnVal > 0 ) // A socket was connected
	{
		m_Destination = destination;
		m_Connected = true;

		SetNoDelay();

		Logger::Log( "Connection attempt to " + destination.GetPrintableAddressAndPort() + " was successfull!", "TCPSocket", LogSeverity::INFO_MSG );
		return true;
	}
	else if ( returnVal == 0 )
	{
		Logger::Log( "Connection attempt to " + destination.GetPrintableAddressAndPort() + " timed out", "TCPSocket", LogSeverity::INFO_MSG );
		return false;
	}
	else
	{
		LogErrorMessage( "Connection attempt to " + destination.GetPrintableAddressAndPort() + " failed", "TCPSocket" );
		return false;
	}
}