BaseNetworkManager.cs 9.5 KB

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