Best way to create IPEndpoint from string

This is one solution…

public static IPEndPoint CreateIPEndPoint(string endPoint)
{
    string[] ep = endPoint.Split(':');
    if(ep.Length != 2) throw new FormatException("Invalid endpoint format");
    IPAddress ip;
    if(!IPAddress.TryParse(ep[0], out ip))
    {
        throw new FormatException("Invalid ip-adress");
    }
    int port;
    if(!int.TryParse(ep[1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
    {
        throw new FormatException("Invalid port");
    }
    return new IPEndPoint(ip, port);
}

Edit: Added a version that will handle IPv4 and IPv6 the previous one only handles IPv4.

// Handles IPv4 and IPv6 notation.
public static IPEndPoint CreateIPEndPoint(string endPoint)
{
    string[] ep = endPoint.Split(':');
    if (ep.Length < 2) throw new FormatException("Invalid endpoint format");
    IPAddress ip;
    if (ep.Length > 2)
    {
        if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out ip))
        {
            throw new FormatException("Invalid ip-adress");
        }
    }
    else
    {
        if (!IPAddress.TryParse(ep[0], out ip))
        {
            throw new FormatException("Invalid ip-adress");
        }
    }
    int port;
    if (!int.TryParse(ep[ep.Length - 1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
    {
        throw new FormatException("Invalid port");
    }
    return new IPEndPoint(ip, port);
}

Leave a Comment