BaseNetworkManager.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.NetworkInformation;
  7. using System.Net.Sockets;
  8. namespace MediaBrowser.Common.Implementations.Networking
  9. {
  10. public abstract class BaseNetworkManager
  11. {
  12. /// <summary>
  13. /// Gets the machine's local ip address
  14. /// </summary>
  15. /// <returns>IPAddress.</returns>
  16. public IEnumerable<string> GetLocalIpAddresses()
  17. {
  18. var list = GetIPsDefault().Where(i => !IPAddress.IsLoopback(i)).Select(i => i.ToString()).ToList();
  19. if (list.Count > 0)
  20. {
  21. return list;
  22. }
  23. return GetLocalIpAddressesFallback();
  24. }
  25. public bool IsInLocalNetwork(string endpoint)
  26. {
  27. if (string.IsNullOrWhiteSpace(endpoint))
  28. {
  29. throw new ArgumentNullException("endpoint");
  30. }
  31. IPAddress address;
  32. if (!IPAddress.TryParse(endpoint, out address))
  33. {
  34. return true;
  35. }
  36. const int lengthMatch = 4;
  37. if (endpoint.Length >= lengthMatch)
  38. {
  39. var prefix = endpoint.Substring(0, lengthMatch);
  40. if (GetLocalIpAddresses()
  41. .Any(i => i.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  42. {
  43. return true;
  44. }
  45. }
  46. // Private address space:
  47. // http://en.wikipedia.org/wiki/Private_network
  48. return
  49. // If url was requested with computer name, we may see this
  50. endpoint.IndexOf("::", StringComparison.OrdinalIgnoreCase) != -1 ||
  51. endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase) ||
  52. endpoint.StartsWith("192.", StringComparison.OrdinalIgnoreCase) ||
  53. endpoint.StartsWith("172.", StringComparison.OrdinalIgnoreCase) ||
  54. endpoint.StartsWith("169.", StringComparison.OrdinalIgnoreCase);
  55. }
  56. private IEnumerable<IPAddress> GetIPsDefault()
  57. {
  58. foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
  59. {
  60. var props = adapter.GetIPProperties();
  61. var gateways = from ga in props.GatewayAddresses
  62. where !ga.Address.Equals(IPAddress.Any)
  63. select true;
  64. if (!gateways.Any())
  65. {
  66. continue;
  67. }
  68. foreach (var uni in props.UnicastAddresses)
  69. {
  70. var address = uni.Address;
  71. if (address.AddressFamily != AddressFamily.InterNetwork)
  72. {
  73. continue;
  74. }
  75. yield return address;
  76. }
  77. }
  78. }
  79. private IEnumerable<string> GetLocalIpAddressesFallback()
  80. {
  81. var host = Dns.GetHostEntry(Dns.GetHostName());
  82. // Reverse them because the last one is usually the correct one
  83. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  84. return host.AddressList
  85. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  86. .Select(i => i.ToString())
  87. .Reverse();
  88. }
  89. /// <summary>
  90. /// Gets a random port number that is currently available
  91. /// </summary>
  92. /// <returns>System.Int32.</returns>
  93. public int GetRandomUnusedPort()
  94. {
  95. var listener = new TcpListener(IPAddress.Any, 0);
  96. listener.Start();
  97. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  98. listener.Stop();
  99. return port;
  100. }
  101. /// <summary>
  102. /// Returns MAC Address from first Network Card in Computer
  103. /// </summary>
  104. /// <returns>[string] MAC Address</returns>
  105. public string GetMacAddress()
  106. {
  107. return NetworkInterface.GetAllNetworkInterfaces()
  108. .Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
  109. .Select(i => BitConverter.ToString(i.GetPhysicalAddress().GetAddressBytes()))
  110. .FirstOrDefault();
  111. }
  112. /// <summary>
  113. /// Parses the specified endpointstring.
  114. /// </summary>
  115. /// <param name="endpointstring">The endpointstring.</param>
  116. /// <returns>IPEndPoint.</returns>
  117. public IPEndPoint Parse(string endpointstring)
  118. {
  119. return Parse(endpointstring, -1);
  120. }
  121. /// <summary>
  122. /// Parses the specified endpointstring.
  123. /// </summary>
  124. /// <param name="endpointstring">The endpointstring.</param>
  125. /// <param name="defaultport">The defaultport.</param>
  126. /// <returns>IPEndPoint.</returns>
  127. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  128. /// <exception cref="System.FormatException"></exception>
  129. private static IPEndPoint Parse(string endpointstring, int defaultport)
  130. {
  131. if (String.IsNullOrEmpty(endpointstring)
  132. || endpointstring.Trim().Length == 0)
  133. {
  134. throw new ArgumentException("Endpoint descriptor may not be empty.");
  135. }
  136. if (defaultport != -1 &&
  137. (defaultport < IPEndPoint.MinPort
  138. || defaultport > IPEndPoint.MaxPort))
  139. {
  140. throw new ArgumentException(String.Format("Invalid default port '{0}'", defaultport));
  141. }
  142. string[] values = endpointstring.Split(new char[] { ':' });
  143. IPAddress ipaddy;
  144. int port = -1;
  145. //check if we have an IPv6 or ports
  146. if (values.Length <= 2) // ipv4 or hostname
  147. {
  148. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  149. //try to use the address as IPv4, otherwise get hostname
  150. if (!IPAddress.TryParse(values[0], out ipaddy))
  151. ipaddy = GetIPfromHost(values[0]);
  152. }
  153. else if (values.Length > 2) //ipv6
  154. {
  155. //could [a:b:c]:d
  156. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  157. {
  158. string ipaddressstring = String.Join(":", values.Take(values.Length - 1).ToArray());
  159. ipaddy = IPAddress.Parse(ipaddressstring);
  160. port = GetPort(values[values.Length - 1]);
  161. }
  162. else //[a:b:c] or a:b:c
  163. {
  164. ipaddy = IPAddress.Parse(endpointstring);
  165. port = defaultport;
  166. }
  167. }
  168. else
  169. {
  170. throw new FormatException(String.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  171. }
  172. if (port == -1)
  173. throw new ArgumentException(String.Format("No port specified: '{0}'", endpointstring));
  174. return new IPEndPoint(ipaddy, port);
  175. }
  176. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  177. /// <summary>
  178. /// Gets the port.
  179. /// </summary>
  180. /// <param name="p">The p.</param>
  181. /// <returns>System.Int32.</returns>
  182. /// <exception cref="System.FormatException"></exception>
  183. private static int GetPort(string p)
  184. {
  185. int port;
  186. if (!Int32.TryParse(p, out port)
  187. || port < IPEndPoint.MinPort
  188. || port > IPEndPoint.MaxPort)
  189. {
  190. throw new FormatException(String.Format("Invalid end point port '{0}'", p));
  191. }
  192. return port;
  193. }
  194. /// <summary>
  195. /// Gets the I pfrom host.
  196. /// </summary>
  197. /// <param name="p">The p.</param>
  198. /// <returns>IPAddress.</returns>
  199. /// <exception cref="System.ArgumentException"></exception>
  200. private static IPAddress GetIPfromHost(string p)
  201. {
  202. var hosts = Dns.GetHostAddresses(p);
  203. if (hosts == null || hosts.Length == 0)
  204. throw new ArgumentException(String.Format("Host not found: {0}", p));
  205. return hosts[0];
  206. }
  207. }
  208. }