示例#1
0
NETWORK_API void NetworkUtility::GetIPAndPortFromString( const rString& input, rString& outIP, unsigned short& outPort )
{
	if ( input == "" )
		return;

	outIP	= "";
	outPort = INVALID_PORT;

	size_t colonCount = std::count( input.begin(), input.end(), ':' );

	if ( colonCount == 1 )
	{
		outIP = GetIPFromString( input );
		size_t colonPosition = input.find( ':' );
		rString portString = input.substr( colonPosition + 1 );
		if ( StringUtility::IsDigitsOnly( portString ) )
		{
			outPort = GetPortFromString( portString );
		}
	}
	else if ( StringUtility::IsDigitsOnly( input ) )
	{
		outPort = GetPortFromString( input );
	}
	else
	{
		outIP = GetIPFromString( input );
	}
}
示例#2
0
rString NetworkUtility::GetIPFromDNS( const rString& input )
{
	rString ip = "";
	size_t colonPos = input.find_first_of( ":" );
	rString dns = input;
	if ( colonPos != std::string::npos )
		dns = input.substr( 0, colonPos );

	addrinfo*	result	= nullptr;
	addrinfo	hints;

	memset(&hints, 0, sizeof( addrinfo ) );
	hints.ai_family		= AF_INET; // TODODB: When IPv6 implemented change this to AF_UNSPEC, for now force IPv4
	hints.ai_socktype	= SOCK_STREAM;
	hints.ai_protocol	= IPPROTO_TCP;

#if PLATFORM == PLATFORM_WINDOWS
	DWORD returnValue;
#elif PLATFORM == PLATFORM_LINUX
	int returnValue;
#endif

	returnValue	= getaddrinfo( dns.c_str(), nullptr, &hints, &result );

	if ( returnValue != 0 )
	{
		// TODODB: Handle dns lookup failure somehow
		Logger::Log( "Failed DNS lookup with error: " + rString( gai_strerror( returnValue ) ), "Network", LogSeverity::WARNING_MSG );
		return ip;
	}

	// result will be a linked list, use the first entry
	void *addr;
	if(result->ai_family == AF_INET)
	{
		sockaddr_in *ipv4 = (struct sockaddr_in *)result->ai_addr;
		addr = &(ipv4->sin_addr);

		char ipstr[INET_ADDRSTRLEN];
		// convert the IP to a string and print it:
		inet_ntop(result->ai_family, addr, ipstr, sizeof( ipstr ) );
		ip = rString( ipstr );
	}
	// TODODB: Handle IPv6 when implemented and move inet_ntop to relevant place
	//} else { // Is IPv6
	//struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
	//addr = &(ipv6->sin6_addr);
	//}

	// Free the linked list	
	freeaddrinfo( result );
	return ip;
}