/*
	Lan Wars.
	Copyright (c) 2009, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		Class representing an IPV4 address and port.
//=====================================================================================================================

#include "Precompiled.h"
#include "Network\NetworkAddress.h"
#include "Network\NetworkCore.h"

using namespace Game;
			
//=====================================================================================================================				
/// @brief		Returns the ip address of the given host
/// @param		host_name - name or dotted decimal ip address of the host
/// @remarks	If the host name cannot be resolved, an invalid IP address of 255.255.255.255 is used
/// @pre		The given host name or address cannot be null
/// @pre		The network core system should have been initialized
//=====================================================================================================================

unsigned NetworkAddress::GetHostIP( const char * host_name )
{
	// Make sure ok:
	
	ENSURE( host_name						, "The given host name or address cannot be null"			)
	ENSURE( NetworkCore::IsInitialized()	, "The network core system should have been initialized"	)
	
	// Make sure the name is not zero length:
	
	if ( host_name[0] )
	{
		// Right: try and convert the address from a string into an ip
		
		unsigned address = inet_addr(host_name);
		
		// See if that fared ok:
		
		if ( address == 0xffffffff )
		{
			// That failed: assume it is a host name and try to resolve using dns
			
			hostent * result = gethostbyname(host_name);
			
			// See if that went ok:
			
			if ( result )
			{
				// Make sure the first address is given:
				
				if ( result->h_addr_list[0] )
				{
					// Get this address:
					
					unsigned address = *((unsigned*)(result->h_addr_list[0]));

					// Return
						
					return ntohl(address);
				}
				else
				{
					// Not given: 
					
					return 0xffffffff;
				}
			}
			else
			{
				// If using the console then print what happened:
				
				#ifdef USE_DEBUG_CONSOLE
				
					DebugConsole::Print("\n##ERROR resolving host name for an ip address:\n\n");
					DebugConsole::Print( NetworkCore::GetErrorString() );
				
				#endif
				
				// Clear the last error:
				
				NetworkCore::ClearError();
				
				// Return an invalid ip
				
				return 0xffffffff;
			}
		}
		else
		{
			// That was ok: return the ip
			
			return address;
		}
	}
	else
	{
		// Invalid address:
		
		return 0xffffffff;
	}
}

//=====================================================================================================================
/// @brief		attempts to return the name of the host attached to the given ip address.
/// @param		ip - ip to get the host name for
/// @returns	Name of the host or a blank string on failure
/// @remarks	The ip address should be given in the format whereby the low order byte is the first part of the 
///				dotted decimal address and whereby the the high order byte is the last part
//=====================================================================================================================

std::string NetworkAddress::GetHostName( unsigned ip )
{
	// Need to convert the address to network order
	
	unsigned na = htonl(ip);

	// Try and get the address:
	
	hostent * result = gethostbyaddr((const char*)(&na),sizeof(unsigned),AF_INET);
	
	// See if successful:
	
	if ( result )
	{
		// Good return the name:
		
		return std::string(result->h_name);
	}
	else
	{
		// If using the console then print what happened:
		
		#ifdef USE_DEBUG_CONSOLE
		
			DebugConsole::Print("\n##ERROR resolving host ip to a name:\n\n");
			DebugConsole::Print( NetworkCore::GetErrorString() );
		
		#endif
		
		// Clear the last error:
		
		NetworkCore::ClearError();

		// Fail: return a blank string
		
		return std::string("");
	}
}
