Best way to create IPEndpoint from string

后端 未结 13 2006
失恋的感觉
失恋的感觉 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:15

    Here is my version of parsing text to IPEndPoint:

    private static IPEndPoint ParseIPEndPoint(string text)
    {
        Uri uri;
        if (Uri.TryCreate(text, UriKind.Absolute, out uri))
            return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
        if (Uri.TryCreate(String.Concat("tcp://", text), UriKind.Absolute, out uri))
            return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
        if (Uri.TryCreate(String.Concat("tcp://", String.Concat("[", text, "]")), UriKind.Absolute, out uri))
            return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
        throw new FormatException("Failed to parse text to IPEndPoint");
    }
    

    Tested with:

    • 0.0.0.0
    • 0.0.0.0:100
    • [::1]:100
    • [::1]:0
    • ::1
    • [2001:db8:85a3:8d3:1319:8a2e:370:7348]
    • [2001:db8:85a3:8d3:1319:8a2e:370:7348]:100
    • http://0.0.0.0
    • http://0.0.0.0:100
    • http://[::1]
    • http://[::1]:100
    • https://0.0.0.0
    • https://[::1]

提交回复
热议问题