BaseNetworkManager.cs 10 KB

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