BaseNetworkManager.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Net.Sockets;
  9. namespace MediaBrowser.Common.Implementations.Networking
  10. {
  11. public abstract class BaseNetworkManager
  12. {
  13. protected ILogger Logger { get; private set; }
  14. protected BaseNetworkManager(ILogger logger)
  15. {
  16. Logger = logger;
  17. }
  18. /// <summary>
  19. /// Gets the machine's local ip address
  20. /// </summary>
  21. /// <returns>IPAddress.</returns>
  22. public IEnumerable<string> GetLocalIpAddresses()
  23. {
  24. var list = GetIPsDefault().Where(i => !IPAddress.IsLoopback(i)).Select(i => i.ToString()).ToList();
  25. if (list.Count > 0)
  26. {
  27. return list;
  28. }
  29. return GetLocalIpAddressesFallback();
  30. }
  31. private bool IsInPrivateAddressSpace(string endpoint)
  32. {
  33. // Private address space:
  34. // http://en.wikipedia.org/wiki/Private_network
  35. return
  36. // If url was requested with computer name, we may see this
  37. endpoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 ||
  38. endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  39. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  40. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  41. endpoint.StartsWith("192.", StringComparison.OrdinalIgnoreCase) ||
  42. endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase) ||
  43. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  44. }
  45. public bool IsInLocalNetwork(string endpoint)
  46. {
  47. return IsInLocalNetworkInternal(endpoint, true);
  48. }
  49. public bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
  50. {
  51. if (string.IsNullOrWhiteSpace(endpoint))
  52. {
  53. throw new ArgumentNullException("endpoint");
  54. }
  55. if (IsInPrivateAddressSpace(endpoint))
  56. {
  57. return true;
  58. }
  59. const int lengthMatch = 4;
  60. if (endpoint.Length >= lengthMatch)
  61. {
  62. var prefix = endpoint.Substring(0, lengthMatch);
  63. if (GetLocalIpAddresses()
  64. .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  65. {
  66. return true;
  67. }
  68. }
  69. IPAddress address;
  70. if (resolveHost && !IPAddress.TryParse(endpoint, out address))
  71. {
  72. var host = new Uri(endpoint).DnsSafeHost;
  73. Logger.Debug("Resolving host {0}", host);
  74. try
  75. {
  76. address = GetIpAddresses(host).FirstOrDefault();
  77. if (address != null)
  78. {
  79. Logger.Debug("{0} resolved to {1}", host, address);
  80. return IsInLocalNetworkInternal(address.ToString(), false);
  81. }
  82. }
  83. catch (Exception ex)
  84. {
  85. Logger.ErrorException("Error resovling hostname {0}", ex, host);
  86. }
  87. }
  88. return false;
  89. }
  90. public IEnumerable<IPAddress> GetIpAddresses(string hostName)
  91. {
  92. return Dns.GetHostAddresses(hostName);
  93. }
  94. private IEnumerable<IPAddress> GetIPsDefault()
  95. {
  96. foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
  97. {
  98. var props = adapter.GetIPProperties();
  99. var gateways = from ga in props.GatewayAddresses
  100. where !ga.Address.Equals(IPAddress.Any)
  101. select true;
  102. if (!gateways.Any())
  103. {
  104. continue;
  105. }
  106. foreach (var uni in props.UnicastAddresses)
  107. {
  108. var address = uni.Address;
  109. if (address.AddressFamily != AddressFamily.InterNetwork)
  110. {
  111. continue;
  112. }
  113. yield return address;
  114. }
  115. }
  116. }
  117. private IEnumerable<string> GetLocalIpAddressesFallback()
  118. {
  119. var host = Dns.GetHostEntry(Dns.GetHostName());
  120. // Reverse them because the last one is usually the correct one
  121. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  122. return host.AddressList
  123. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  124. .Select(i => i.ToString())
  125. .Reverse();
  126. }
  127. /// <summary>
  128. /// Gets a random port number that is currently available
  129. /// </summary>
  130. /// <returns>System.Int32.</returns>
  131. public int GetRandomUnusedPort()
  132. {
  133. var listener = new TcpListener(IPAddress.Any, 0);
  134. listener.Start();
  135. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  136. listener.Stop();
  137. return port;
  138. }
  139. /// <summary>
  140. /// Returns MAC Address from first Network Card in Computer
  141. /// </summary>
  142. /// <returns>[string] MAC Address</returns>
  143. public string GetMacAddress()
  144. {
  145. return NetworkInterface.GetAllNetworkInterfaces()
  146. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  147. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  148. .FirstOrDefault();
  149. }
  150. /// <summary>
  151. /// Parses the specified endpointstring.
  152. /// </summary>
  153. /// <param name="endpointstring">The endpointstring.</param>
  154. /// <returns>IPEndPoint.</returns>
  155. public IPEndPoint Parse(string endpointstring)
  156. {
  157. return Parse(endpointstring, -1);
  158. }
  159. /// <summary>
  160. /// Parses the specified endpointstring.
  161. /// </summary>
  162. /// <param name="endpointstring">The endpointstring.</param>
  163. /// <param name="defaultport">The defaultport.</param>
  164. /// <returns>IPEndPoint.</returns>
  165. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  166. /// <exception cref="System.FormatException"></exception>
  167. private static IPEndPoint Parse(string endpointstring, int defaultport)
  168. {
  169. if (String.IsNullOrEmpty(endpointstring)
  170. || endpointstring.Trim().Length == 0)
  171. {
  172. throw new ArgumentException("Endpoint descriptor may not be empty.");
  173. }
  174. if (defaultport != -1 &&
  175. (defaultport < IPEndPoint.MinPort
  176. || defaultport > IPEndPoint.MaxPort))
  177. {
  178. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  179. }
  180. string[] values = endpointstring.Split(new char[] { ':' });
  181. IPAddress ipaddy;
  182. int port = -1;
  183. //check if we have an IPv6 or ports
  184. if (values.Length <= 2) // ipv4 or hostname
  185. {
  186. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  187. //try to use the address as IPv4, otherwise get hostname
  188. if (!IPAddress.TryParse(values[0], out ipaddy))
  189. ipaddy = GetIPfromHost(values[0]);
  190. }
  191. else if (values.Length > 2) //ipv6
  192. {
  193. //could [a:b:c]:d
  194. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  195. {
  196. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  197. ipaddy = IPAddress.Parse(ipaddressstring);
  198. port = GetPort(values[values.Length - 1]);
  199. }
  200. else //[a:b:c] or a:b:c
  201. {
  202. ipaddy = IPAddress.Parse(endpointstring);
  203. port = defaultport;
  204. }
  205. }
  206. else
  207. {
  208. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  209. }
  210. if (port == -1)
  211. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  212. return new IPEndPoint(ipaddy, port);
  213. }
  214. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  215. /// <summary>
  216. /// Gets the port.
  217. /// </summary>
  218. /// <param name="p">The p.</param>
  219. /// <returns>System.Int32.</returns>
  220. /// <exception cref="System.FormatException"></exception>
  221. private static int GetPort(string p)
  222. {
  223. int port;
  224. if (!Int32.TryParse(p, out port)
  225. || port < IPEndPoint.MinPort
  226. || port > IPEndPoint.MaxPort)
  227. {
  228. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  229. }
  230. return port;
  231. }
  232. /// <summary>
  233. /// Gets the I pfrom host.
  234. /// </summary>
  235. /// <param name="p">The p.</param>
  236. /// <returns>IPAddress.</returns>
  237. /// <exception cref="System.ArgumentException"></exception>
  238. private static IPAddress GetIPfromHost(string p)
  239. {
  240. var hosts = Dns.GetHostAddresses(p);
  241. if (hosts == null || hosts.Length == 0)
  242. throw new ArgumentException(String.Format("Host not found: {0}", p));
  243. return hosts[0];
  244. }
  245. }
  246. }