BaseNetworkManager.cs 10 KB

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