Best way to create IPEndpoint from string

后端 未结 13 1906
失恋的感觉
失恋的感觉 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 06:57

    Create an extension method Parse and TryParse. I guess that is more elegant.

    0 讨论(0)
  • 2020-12-03 06:59

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 07:01
    IPAddress ipAddress = IPAddress.Parse(yourIPAddress);
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Convert.ToInt16(yourPortAddress));
    
    0 讨论(0)
  • 2020-12-03 07:02

    Here is a very simple solution, it handles both IPv4 and IPv6.

    public class IPEndPoint : System.Net.IPEndPoint
    {
        public IPEndPoint(long address, int port) : base(address, port) { }
        public IPEndPoint(IPAddress address, int port) : base(address, port) { }
    
        public static bool TryParse(string value, out IPEndPoint result)
        {
            if (!Uri.TryCreate($"tcp://{value}", UriKind.Absolute, out Uri uri) ||
                !IPAddress.TryParse(uri.Host, out IPAddress ipAddress) ||
                uri.Port < 0 || uri.Port > 65535)
            {
                result = default(IPEndPoint);
                return false;
            }
    
            result = new IPEndPoint(ipAddress, uri.Port);
            return true;
        }
    }
    

    Simply use the TryParse the way you would normally.

    IPEndPoint.TryParse("192.168.1.10:80", out IPEndPoint ipv4Result);
    IPEndPoint.TryParse("[fd00::]:8080", out IPEndPoint ipv6Result);
    
    0 讨论(0)
  • 2020-12-03 07:05
    using System;
    using System.Net;
    
    static class Helper {
      public static IPEndPoint ToIPEndPoint(this string value, int port = IPEndPoint.MinPort) {
        if (string.IsNullOrEmpty(value) || ! IPAddress.TryParse(value, out var address)) 
          return null;
        var offset = (value = value.Replace(address.ToString(), string.Empty)).LastIndexOf(':');
        if (offset >= 0)
          if (! int.TryParse(value.Substring(offset + 1), out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            return null;
        return new IPEndPoint(address, port);
      }
    }
    
    class Program {
      static void Main() {
        foreach (var sample in new [] {
          // See https://docops.ca.com/ca-data-protection-15/en/implementing/platform-deployment/technical-information/ipv6-address-and-port-formats
          "192.168.0.3",
          "fe80::214:c2ff:fec8:c920",
          "10.0.1.53-10.0.1.80",
          "10.0",
          "10/7",
          "2001:0db8:85a3/48",
          "192.168.0.5:10",
          "[fe80::e828:209d:20e:c0ae]:375",
          ":137-139",
          "192.168:1024-65535",
          "[fe80::]-[fe81::]:80"
        }) {
          var point = sample.ToIPEndPoint();
          var report = point == null ? "NULL" : $@"IPEndPoint {{
      Address: {point.Address}
      AddressFamily: {point.AddressFamily}
      Port: {point.Port}
    }}";
          Console.WriteLine($@"""{sample}"" to IPEndPoint is {report}
    ");
        }
      }
    }
    
    0 讨论(0)
  • 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;
        }
    
    0 讨论(0)
提交回复
热议问题