Best way to create IPEndpoint from string

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

    This is my take on the parsing of an IPEndPoint. Using the Uri class avoids having to handle the specifics of IPv4/6, and the presence or not of the port. You could can modify the default port for your application.

        public static bool TryParseEndPoint(string ipPort, out System.Net.IPEndPoint result)
        {
            result = null;
    
            string scheme = "iiiiiiiiiaigaig";
            GenericUriParserOptions options =
                GenericUriParserOptions.AllowEmptyAuthority |
                GenericUriParserOptions.NoQuery |
                GenericUriParserOptions.NoUserInfo |
                GenericUriParserOptions.NoFragment |
                GenericUriParserOptions.DontCompressPath |
                GenericUriParserOptions.DontConvertPathBackslashes |
                GenericUriParserOptions.DontUnescapePathDotsAndSlashes;
            UriParser.Register(new GenericUriParser(options), scheme, 1337);
    
            Uri parsedUri;
            if (!Uri.TryCreate(scheme + "://" + ipPort, UriKind.Absolute, out parsedUri))
                return false;
            System.Net.IPAddress parsedIP;
            if (!System.Net.IPAddress.TryParse(parsedUri.Host, out parsedIP))
                return false;
    
            result = new System.Net.IPEndPoint(parsedIP, parsedUri.Port);
            return true;
        }
    

提交回复
热议问题