BaseNetworkManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. using MoreLinq;
  10. namespace MediaBrowser.Common.Implementations.Networking
  11. {
  12. public abstract class BaseNetworkManager
  13. {
  14. protected ILogger Logger { get; private set; }
  15. private DateTime _lastRefresh;
  16. protected BaseNetworkManager(ILogger logger)
  17. {
  18. Logger = logger;
  19. }
  20. private List<IPAddress> _localIpAddresses;
  21. private readonly object _localIpAddressSyncLock = new object();
  22. /// <summary>
  23. /// Gets the machine's local ip address
  24. /// </summary>
  25. /// <returns>IPAddress.</returns>
  26. public IEnumerable<IPAddress> GetLocalIpAddresses()
  27. {
  28. const int cacheMinutes = 5;
  29. lock (_localIpAddressSyncLock)
  30. {
  31. var forceRefresh = (DateTime.UtcNow - _lastRefresh).TotalMinutes >= cacheMinutes;
  32. if (_localIpAddresses == null || forceRefresh)
  33. {
  34. var addresses = GetLocalIpAddressesInternal().ToList();
  35. _localIpAddresses = addresses;
  36. _lastRefresh = DateTime.UtcNow;
  37. return addresses;
  38. }
  39. }
  40. return _localIpAddresses;
  41. }
  42. private IEnumerable<IPAddress> GetLocalIpAddressesInternal()
  43. {
  44. var list = GetIPsDefault()
  45. .ToList();
  46. if (list.Count == 0)
  47. {
  48. list.AddRange(GetLocalIpAddressesFallback());
  49. }
  50. return list.Where(FilterIpAddress).DistinctBy(i => i.ToString());
  51. }
  52. private bool FilterIpAddress(IPAddress address)
  53. {
  54. var addressString = address.ToString ();
  55. if (addressString.StartsWith("169.", StringComparison.OrdinalIgnoreCase))
  56. {
  57. return false;
  58. }
  59. return true;
  60. }
  61. public bool IsInPrivateAddressSpace(string endpoint)
  62. {
  63. if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
  64. {
  65. return true;
  66. }
  67. // Handle ipv4 mapped to ipv6
  68. endpoint = endpoint.Replace("::ffff:", string.Empty);
  69. // Private address space:
  70. // http://en.wikipedia.org/wiki/Private_network
  71. if (endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase))
  72. {
  73. return Is172AddressPrivate(endpoint);
  74. }
  75. return
  76. endpoint.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ||
  77. endpoint.StartsWith("127.", StringComparison.OrdinalIgnoreCase) ||
  78. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  79. endpoint.StartsWith("192.168", StringComparison.OrdinalIgnoreCase) ||
  80. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  81. }
  82. private bool Is172AddressPrivate(string endpoint)
  83. {
  84. for (var i = 16; i <= 31; i++)
  85. {
  86. if (endpoint.StartsWith("172." + i.ToString(CultureInfo.InvariantCulture) + ".", StringComparison.OrdinalIgnoreCase))
  87. {
  88. return true;
  89. }
  90. }
  91. return false;
  92. }
  93. public bool IsInLocalNetwork(string endpoint)
  94. {
  95. return IsInLocalNetworkInternal(endpoint, true);
  96. }
  97. public bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
  98. {
  99. if (string.IsNullOrWhiteSpace(endpoint))
  100. {
  101. throw new ArgumentNullException("endpoint");
  102. }
  103. IPAddress address;
  104. if (IPAddress.TryParse(endpoint, out address))
  105. {
  106. var addressString = address.ToString();
  107. int lengthMatch = 100;
  108. if (address.AddressFamily == AddressFamily.InterNetwork)
  109. {
  110. lengthMatch = 4;
  111. if (IsInPrivateAddressSpace(addressString))
  112. {
  113. return true;
  114. }
  115. }
  116. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  117. {
  118. lengthMatch = 10;
  119. if (IsInPrivateAddressSpace(endpoint))
  120. {
  121. return true;
  122. }
  123. }
  124. // Should be even be doing this with ipv6?
  125. if (addressString.Length >= lengthMatch)
  126. {
  127. var prefix = addressString.Substring(0, lengthMatch);
  128. if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  129. {
  130. return true;
  131. }
  132. }
  133. }
  134. else if (resolveHost)
  135. {
  136. Uri uri;
  137. if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out uri))
  138. {
  139. try
  140. {
  141. var host = uri.DnsSafeHost;
  142. Logger.Debug("Resolving host {0}", host);
  143. address = GetIpAddresses(host).FirstOrDefault();
  144. if (address != null)
  145. {
  146. Logger.Debug("{0} resolved to {1}", host, address);
  147. return IsInLocalNetworkInternal(address.ToString(), false);
  148. }
  149. }
  150. catch (InvalidOperationException)
  151. {
  152. // Can happen with reverse proxy or IIS url rewriting
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.ErrorException("Error resovling hostname", ex);
  157. }
  158. }
  159. }
  160. return false;
  161. }
  162. public IEnumerable<IPAddress> GetIpAddresses(string hostName)
  163. {
  164. return Dns.GetHostAddresses(hostName);
  165. }
  166. private List<IPAddress> GetIPsDefault()
  167. {
  168. NetworkInterface[] interfaces;
  169. try
  170. {
  171. interfaces = NetworkInterface.GetAllNetworkInterfaces();
  172. }
  173. catch (Exception ex)
  174. {
  175. Logger.ErrorException("Error in GetAllNetworkInterfaces", ex);
  176. return new List<IPAddress>();
  177. }
  178. return interfaces.SelectMany(network => {
  179. try
  180. {
  181. Logger.Debug("Querying interface: {0}. Type: {1}. Status: {2}", network.Name, network.NetworkInterfaceType, network.OperationalStatus);
  182. var properties = network.GetIPProperties();
  183. return properties.UnicastAddresses
  184. .Where(i => i.IsDnsEligible)
  185. .Select(i => i.Address)
  186. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  187. .ToList();
  188. }
  189. catch (Exception ex)
  190. {
  191. Logger.ErrorException("Error querying network interface", ex);
  192. return new List<IPAddress>();
  193. }
  194. }).DistinctBy(i => i.ToString())
  195. .ToList();
  196. }
  197. private IEnumerable<IPAddress> GetLocalIpAddressesFallback()
  198. {
  199. var host = Dns.GetHostEntry(Dns.GetHostName());
  200. // Reverse them because the last one is usually the correct one
  201. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  202. return host.AddressList
  203. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  204. .Reverse();
  205. }
  206. /// <summary>
  207. /// Gets a random port number that is currently available
  208. /// </summary>
  209. /// <returns>System.Int32.</returns>
  210. public int GetRandomUnusedPort()
  211. {
  212. var listener = new TcpListener(IPAddress.Any, 0);
  213. listener.Start();
  214. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  215. listener.Stop();
  216. return port;
  217. }
  218. /// <summary>
  219. /// Returns MAC Address from first Network Card in Computer
  220. /// </summary>
  221. /// <returns>[string] MAC Address</returns>
  222. public string GetMacAddress()
  223. {
  224. return NetworkInterface.GetAllNetworkInterfaces()
  225. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  226. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  227. .FirstOrDefault();
  228. }
  229. /// <summary>
  230. /// Parses the specified endpointstring.
  231. /// </summary>
  232. /// <param name="endpointstring">The endpointstring.</param>
  233. /// <returns>IPEndPoint.</returns>
  234. public IPEndPoint Parse(string endpointstring)
  235. {
  236. return Parse(endpointstring, -1);
  237. }
  238. /// <summary>
  239. /// Parses the specified endpointstring.
  240. /// </summary>
  241. /// <param name="endpointstring">The endpointstring.</param>
  242. /// <param name="defaultport">The defaultport.</param>
  243. /// <returns>IPEndPoint.</returns>
  244. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  245. /// <exception cref="System.FormatException"></exception>
  246. private static IPEndPoint Parse(string endpointstring, int defaultport)
  247. {
  248. if (String.IsNullOrEmpty(endpointstring)
  249. || endpointstring.Trim().Length == 0)
  250. {
  251. throw new ArgumentException("Endpoint descriptor may not be empty.");
  252. }
  253. if (defaultport != -1 &&
  254. (defaultport < IPEndPoint.MinPort
  255. || defaultport > IPEndPoint.MaxPort))
  256. {
  257. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  258. }
  259. string[] values = endpointstring.Split(new char[] { ':' });
  260. IPAddress ipaddy;
  261. int port = -1;
  262. //check if we have an IPv6 or ports
  263. if (values.Length <= 2) // ipv4 or hostname
  264. {
  265. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  266. //try to use the address as IPv4, otherwise get hostname
  267. if (!IPAddress.TryParse(values[0], out ipaddy))
  268. ipaddy = GetIPfromHost(values[0]);
  269. }
  270. else if (values.Length > 2) //ipv6
  271. {
  272. //could [a:b:c]:d
  273. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  274. {
  275. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  276. ipaddy = IPAddress.Parse(ipaddressstring);
  277. port = GetPort(values[values.Length - 1]);
  278. }
  279. else //[a:b:c] or a:b:c
  280. {
  281. ipaddy = IPAddress.Parse(endpointstring);
  282. port = defaultport;
  283. }
  284. }
  285. else
  286. {
  287. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  288. }
  289. if (port == -1)
  290. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  291. return new IPEndPoint(ipaddy, port);
  292. }
  293. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  294. /// <summary>
  295. /// Gets the port.
  296. /// </summary>
  297. /// <param name="p">The p.</param>
  298. /// <returns>System.Int32.</returns>
  299. /// <exception cref="System.FormatException"></exception>
  300. private static int GetPort(string p)
  301. {
  302. int port;
  303. if (!Int32.TryParse(p, out port)
  304. || port < IPEndPoint.MinPort
  305. || port > IPEndPoint.MaxPort)
  306. {
  307. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  308. }
  309. return port;
  310. }
  311. /// <summary>
  312. /// Gets the I pfrom host.
  313. /// </summary>
  314. /// <param name="p">The p.</param>
  315. /// <returns>IPAddress.</returns>
  316. /// <exception cref="System.ArgumentException"></exception>
  317. private static IPAddress GetIPfromHost(string p)
  318. {
  319. var hosts = Dns.GetHostAddresses(p);
  320. if (hosts == null || hosts.Length == 0)
  321. throw new ArgumentException(String.Format("Host not found: {0}", p));
  322. return hosts[0];
  323. }
  324. }
  325. }