Since IPEndpoint
contains a ToString()
method that outputs:
10.10.10.10:1010
There should also be
This will do IPv4 and IPv6. An extension method for this functionality would be on System.string. Not sure I want this option for every string I have in the project.
private static IPEndPoint IPEndPointParse(string endpointstring)
{
string[] values = endpointstring.Split(new char[] {':'});
if (2 > values.Length)
{
throw new FormatException("Invalid endpoint format");
}
IPAddress ipaddress;
string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray());
if (!IPAddress.TryParse(ipaddressstring, out ipaddress))
{
throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", ipaddressstring));
}
int port;
if (!int.TryParse(values[values.Length - 1], out port)
|| port < IPEndPoint.MinPort
|| port > IPEndPoint.MaxPort)
{
throw new FormatException(string.Format("Invalid end point port '{0}'", values[values.Length - 1]));
}
return new IPEndPoint(ipaddress, port);
}