ListenerPrefix.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Net;
  3. namespace SocketHttpListener.Net
  4. {
  5. internal sealed class ListenerPrefix
  6. {
  7. private string _original;
  8. private string _host;
  9. private ushort _port;
  10. private string _path;
  11. private bool _secure;
  12. private IPAddress[] _addresses;
  13. internal HttpListener _listener;
  14. public ListenerPrefix(string prefix)
  15. {
  16. _original = prefix;
  17. Parse(prefix);
  18. }
  19. public override string ToString()
  20. {
  21. return _original;
  22. }
  23. public IPAddress[] Addresses
  24. {
  25. get => _addresses;
  26. set => _addresses = value;
  27. }
  28. public bool Secure => _secure;
  29. public string Host => _host;
  30. public int Port => _port;
  31. public string Path => _path;
  32. // Equals and GetHashCode are required to detect duplicates in HttpListenerPrefixCollection.
  33. public override bool Equals(object o)
  34. {
  35. var other = o as ListenerPrefix;
  36. if (other == null)
  37. return false;
  38. return (_original == other._original);
  39. }
  40. public override int GetHashCode()
  41. {
  42. return _original.GetHashCode();
  43. }
  44. private void Parse(string uri)
  45. {
  46. ushort default_port = 80;
  47. if (uri.StartsWith("https://"))
  48. {
  49. default_port = 443;
  50. _secure = true;
  51. }
  52. int length = uri.Length;
  53. int start_host = uri.IndexOf(':') + 3;
  54. if (start_host >= length)
  55. throw new ArgumentException("net_listener_host");
  56. int colon = uri.IndexOf(':', start_host, length - start_host);
  57. int root;
  58. if (colon > 0)
  59. {
  60. _host = uri.Substring(start_host, colon - start_host);
  61. root = uri.IndexOf('/', colon, length - colon);
  62. _port = (ushort)int.Parse(uri.Substring(colon + 1, root - colon - 1));
  63. _path = uri.Substring(root);
  64. }
  65. else
  66. {
  67. root = uri.IndexOf('/', start_host, length - start_host);
  68. _host = uri.Substring(start_host, root - start_host);
  69. _port = default_port;
  70. _path = uri.Substring(root);
  71. }
  72. if (_path.Length != 1)
  73. _path = _path.Substring(0, _path.Length - 1);
  74. }
  75. }
  76. }