.NET Fiddle

CSharp · Console

/Program.cs

using System;
					
public class Program
{
	public static void Main()
	{
		string fullAddress = GetFullAddressFromHostAndPort("[1fff:0:a88:85a3::ac1f]",6000);
		Console.WriteLine(fullAddress);
		
		string host;	ushort port;
		bool res = GetHostAndPortFromFullAddress(fullAddress, out host, out port);
		
		Console.WriteLine("host: {0}, port: {1}", host, port);
	}
	
	/// <summary>
	///		Build full address from HOST and PORT
	/// </summary>
	/// <remarks>
	///		Possible formats of addresses:
	///			domain_name:5000
	///			192.168.1.1:5000
	///			[1fff:0:a88:85a3::ac1f]:5000
	///		The address always contains port number (5000 by default) and the host can be IPv4/v6 address or domain name.
	///		If address is empty (e.g. in an intermediate stage), the <see cref="Target"/> address will contain just port number, e.g. ":5000"
	/// </remarks>
	/// <param name="host"> Host of the address. Can be domain name or IPv4/v6 address (needs brackets for IPv6) </param>
	/// <param name="portNum"> Port number from the address. By default it's 5000 </param>
	/// <returns> Address or null if an error occurs </returns>
	private static string GetFullAddressFromHostAndPort(string host, ushort portNum = 5000)
	{
		try
		{
			var uri = new Uri("http://" + host + ":" + portNum);
			// host:address without schema (e.g. 'http://')
			return uri.Authority;
		}
		catch (Exception)
		{
			return ":"+portNum;
		}
	}
	
	/// <summary>
	///		Returns HOST and PORT from the <see cref="Target"/> address field
	/// </summary>
	/// <param name="fullAddress"> 
	/// 	Full URI. Possible formats:
	///			domain_name:5000
	///			192.168.1.1:5000
	///			[1fff:0:a88:85a3::ac1f]:5000
	///		The address always contains port number (5000 by default) and the host can be IPv4/v6 address or domain name.
	///		The address can't contain protocol (e.g. 'tcp://', 'http://', etc.)
	/// </param>
	/// <param name="host"> 
	/// 	Host of the address. Can be domain name or IPv4/v6 address (no brackets for IPv6). It's empty if couldn't parse. 
	/// </param>
	/// <param name="portNum"> 
	/// 	Port number from the address. By default it's 5000 if couldn't parse. 
	/// </param>
	/// <returns> True - parsing was successful, otherwise - False </returns>
	private static bool GetHostAndPortFromFullAddress(string fullAddress, out string host, out ushort portNum)
	{
		host = string.Empty;	portNum = 5000;
		try
		{
			// Use URI class for parsing only
			var uri = new Uri("http://" + fullAddress);
			// get host
			host = uri.DnsSafeHost;
			// get port
			portNum = (ushort)uri.Port;
			return true;
		}
		catch (Exception)
		{
			return false;
		}
	}
}
;