2
0

BaseNetworkManager.cs 12 KB

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