Best way to create IPEndpoint from string

后端 未结 13 2003
失恋的感觉
失恋的感觉 2020-12-03 06:33

Since IPEndpoint contains a ToString() method that outputs:

10.10.10.10:1010

There should also be

13条回答
  •  独厮守ぢ
    2020-12-03 07:10

    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);
    }
    

提交回复
热议问题