ListenerPrefix.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 { return _addresses; }
  26. set { _addresses = value; }
  27. }
  28. public bool Secure
  29. {
  30. get { return _secure; }
  31. }
  32. public string Host
  33. {
  34. get { return _host; }
  35. }
  36. public int Port
  37. {
  38. get { return _port; }
  39. }
  40. public string Path
  41. {
  42. get { return _path; }
  43. }
  44. // Equals and GetHashCode are required to detect duplicates in HttpListenerPrefixCollection.
  45. public override bool Equals(object o)
  46. {
  47. ListenerPrefix other = o as ListenerPrefix;
  48. if (other == null)
  49. return false;
  50. return (_original == other._original);
  51. }
  52. public override int GetHashCode()
  53. {
  54. return _original.GetHashCode();
  55. }
  56. private void Parse(string uri)
  57. {
  58. ushort default_port = 80;
  59. if (uri.StartsWith("https://"))
  60. {
  61. default_port = 443;
  62. _secure = true;
  63. }
  64. int length = uri.Length;
  65. int start_host = uri.IndexOf(':') + 3;
  66. if (start_host >= length)
  67. throw new ArgumentException("net_listener_host");
  68. int colon = uri.IndexOf(':', start_host, length - start_host);
  69. int root;
  70. if (colon > 0)
  71. {
  72. _host = uri.Substring(start_host, colon - start_host);
  73. root = uri.IndexOf('/', colon, length - colon);
  74. _port = (ushort)int.Parse(uri.Substring(colon + 1, root - colon - 1));
  75. _path = uri.Substring(root);
  76. }
  77. else
  78. {
  79. root = uri.IndexOf('/', start_host, length - start_host);
  80. _host = uri.Substring(start_host, root - start_host);
  81. _port = default_port;
  82. _path = uri.Substring(root);
  83. }
  84. if (_path.Length != 1)
  85. _path = _path.Substring(0, _path.Length - 1);
  86. }
  87. }
  88. }