BaseNetworkManager.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.NetworkInformation;
  7. using System.Net.Sockets;
  8. namespace MediaBrowser.Common.Implementations.Networking
  9. {
  10. public abstract class BaseNetworkManager
  11. {
  12. /// <summary>
  13. /// Gets the machine's local ip address
  14. /// </summary>
  15. /// <returns>IPAddress.</returns>
  16. public IEnumerable<string> GetLocalIpAddresses()
  17. {
  18. var host = Dns.GetHostEntry(Dns.GetHostName());
  19. // Reverse them because the last one is usually the correct one
  20. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  21. return host.AddressList
  22. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  23. .Select(i => i.ToString())
  24. .Reverse();
  25. }
  26. /// <summary>
  27. /// Gets a random port number that is currently available
  28. /// </summary>
  29. /// <returns>System.Int32.</returns>
  30. public int GetRandomUnusedPort()
  31. {
  32. var listener = new TcpListener(IPAddress.Any, 0);
  33. listener.Start();
  34. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  35. listener.Stop();
  36. return port;
  37. }
  38. /// <summary>
  39. /// Returns MAC Address from first Network Card in Computer
  40. /// </summary>
  41. /// <returns>[string] MAC Address</returns>
  42. public string GetMacAddress()
  43. {
  44. return NetworkInterface.GetAllNetworkInterfaces()
  45. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  46. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  47. .FirstOrDefault();
  48. }
  49. /// <summary>
  50. /// Parses the specified endpointstring.
  51. /// </summary>
  52. /// <param name="endpointstring">The endpointstring.</param>
  53. /// <returns>IPEndPoint.</returns>
  54. public IPEndPoint Parse(string endpointstring)
  55. {
  56. return Parse(endpointstring, -1);
  57. }
  58. /// <summary>
  59. /// Parses the specified endpointstring.
  60. /// </summary>
  61. /// <param name="endpointstring">The endpointstring.</param>
  62. /// <param name="defaultport">The defaultport.</param>
  63. /// <returns>IPEndPoint.</returns>
  64. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  65. /// <exception cref="System.FormatException"></exception>
  66. private static IPEndPoint Parse(string endpointstring, int defaultport)
  67. {
  68. if (String.IsNullOrEmpty(endpointstring)
  69. || endpointstring.Trim().Length == 0)
  70. {
  71. throw new ArgumentException("Endpoint descriptor may not be empty.");
  72. }
  73. if (defaultport != -1 &&
  74. (defaultport < IPEndPoint.MinPort
  75. || defaultport > IPEndPoint.MaxPort))
  76. {
  77. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  78. }
  79. string[] values = endpointstring.Split(new char[] { ':' });
  80. IPAddress ipaddy;
  81. int port = -1;
  82. //check if we have an IPv6 or ports
  83. if (values.Length <= 2) // ipv4 or hostname
  84. {
  85. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  86. //try to use the address as IPv4, otherwise get hostname
  87. if (!IPAddress.TryParse(values[0], out ipaddy))
  88. ipaddy = GetIPfromHost(values[0]);
  89. }
  90. else if (values.Length > 2) //ipv6
  91. {
  92. //could [a:b:c]:d
  93. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  94. {
  95. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  96. ipaddy = IPAddress.Parse(ipaddressstring);
  97. port = GetPort(values[values.Length - 1]);
  98. }
  99. else //[a:b:c] or a:b:c
  100. {
  101. ipaddy = IPAddress.Parse(endpointstring);
  102. port = defaultport;
  103. }
  104. }
  105. else
  106. {
  107. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  108. }
  109. if (port == -1)
  110. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  111. return new IPEndPoint(ipaddy, port);
  112. }
  113. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  114. /// <summary>
  115. /// Gets the port.
  116. /// </summary>
  117. /// <param name="p">The p.</param>
  118. /// <returns>System.Int32.</returns>
  119. /// <exception cref="System.FormatException"></exception>
  120. private static int GetPort(string p)
  121. {
  122. int port;
  123. if (!Int32.TryParse(p, out port)
  124. || port < IPEndPoint.MinPort
  125. || port > IPEndPoint.MaxPort)
  126. {
  127. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  128. }
  129. return port;
  130. }
  131. /// <summary>
  132. /// Gets the I pfrom host.
  133. /// </summary>
  134. /// <param name="p">The p.</param>
  135. /// <returns>IPAddress.</returns>
  136. /// <exception cref="System.ArgumentException"></exception>
  137. private static IPAddress GetIPfromHost(string p)
  138. {
  139. var hosts = Dns.GetHostAddresses(p);
  140. if (hosts == null || hosts.Length == 0)
  141. throw new ArgumentException(String.Format("Host not found: {0}", p));
  142. return hosts[0];
  143. }
  144. }
  145. }