Best way to create IPEndpoint from string

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

    If the port number is always provided after a ':', the following method may be a more elegant option (in code length instead of efficiency).

    public static IPEndpoint ParseIPEndpoint(string ipEndPoint) {
        int ipAddressLength = ipEndPoint.LastIndexOf(':');
        return new IPEndPoint(
            IPAddress.Parse(ipEndPoint.Substring(0, ipAddressLength)),
            Convert.ToInt32(ipEndPoint.Substring(ipAddressLength + 1)));
    }
    

    It works fine for my simple application without considering complex IP address format.

提交回复
热议问题