BaseNetworkManager.cs 13 KB

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