NetworkManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Model.Net;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Management;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Runtime.InteropServices;
  12. namespace MediaBrowser.Common.Implementations.NetworkManagement
  13. {
  14. /// <summary>
  15. /// Class NetUtils
  16. /// </summary>
  17. public class NetworkManager : INetworkManager
  18. {
  19. /// <summary>
  20. /// Gets the machine's local ip address
  21. /// </summary>
  22. /// <returns>IPAddress.</returns>
  23. public IEnumerable<string> GetLocalIpAddresses()
  24. {
  25. var host = Dns.GetHostEntry(Dns.GetHostName());
  26. // Reverse them because the last one is usually the correct one
  27. // It's not fool-proof so ultimately the consumer will have to examine them and decide
  28. return host.AddressList
  29. .Where(i => i.AddressFamily == AddressFamily.InterNetwork)
  30. .Select(i => i.ToString())
  31. .Reverse();
  32. }
  33. /// <summary>
  34. /// Gets a random port number that is currently available
  35. /// </summary>
  36. /// <returns>System.Int32.</returns>
  37. public int GetRandomUnusedPort()
  38. {
  39. var listener = new TcpListener(IPAddress.Any, 0);
  40. listener.Start();
  41. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  42. listener.Stop();
  43. return port;
  44. }
  45. /// <summary>
  46. /// Creates the netsh URL registration.
  47. /// </summary>
  48. public void AuthorizeHttpListening(string url)
  49. {
  50. var startInfo = new ProcessStartInfo
  51. {
  52. FileName = "netsh",
  53. Arguments = string.Format("http add urlacl url={0} user=\"NT AUTHORITY\\Authenticated Users\"", url),
  54. CreateNoWindow = true,
  55. WindowStyle = ProcessWindowStyle.Hidden,
  56. Verb = "runas",
  57. ErrorDialog = false
  58. };
  59. using (var process = Process.Start(startInfo))
  60. {
  61. process.WaitForExit();
  62. }
  63. }
  64. /// <summary>
  65. /// Adds the windows firewall rule.
  66. /// </summary>
  67. /// <param name="port">The port.</param>
  68. /// <param name="protocol">The protocol.</param>
  69. public void AddSystemFirewallRule(int port, NetworkProtocol protocol)
  70. {
  71. // First try to remove it so we don't end up creating duplicates
  72. RemoveSystemFirewallRule(port, protocol);
  73. var args = string.Format("advfirewall firewall add rule name=\"Port {0}\" dir=in action=allow protocol={1} localport={0}", port, protocol);
  74. RunNetsh(args);
  75. }
  76. /// <summary>
  77. /// Removes the windows firewall rule.
  78. /// </summary>
  79. /// <param name="port">The port.</param>
  80. /// <param name="protocol">The protocol.</param>
  81. public void RemoveSystemFirewallRule(int port, NetworkProtocol protocol)
  82. {
  83. var args = string.Format("advfirewall firewall delete rule name=\"Port {0}\" protocol={1} localport={0}", port, protocol);
  84. RunNetsh(args);
  85. }
  86. /// <summary>
  87. /// Runs the netsh.
  88. /// </summary>
  89. /// <param name="args">The args.</param>
  90. private void RunNetsh(string args)
  91. {
  92. var startInfo = new ProcessStartInfo
  93. {
  94. FileName = "netsh",
  95. Arguments = args,
  96. CreateNoWindow = true,
  97. WindowStyle = ProcessWindowStyle.Hidden,
  98. Verb = "runas",
  99. ErrorDialog = false
  100. };
  101. using (var process = new Process { StartInfo = startInfo })
  102. {
  103. process.Start();
  104. process.WaitForExit();
  105. }
  106. }
  107. /// <summary>
  108. /// Returns MAC Address from first Network Card in Computer
  109. /// </summary>
  110. /// <returns>[string] MAC Address</returns>
  111. public string GetMacAddress()
  112. {
  113. var mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  114. var moc = mc.GetInstances();
  115. var macAddress = String.Empty;
  116. foreach (ManagementObject mo in moc)
  117. {
  118. if (macAddress == String.Empty) // only return MAC Address from first card
  119. {
  120. try
  121. {
  122. if ((bool)mo["IPEnabled"]) macAddress = mo["MacAddress"].ToString();
  123. }
  124. catch
  125. {
  126. mo.Dispose();
  127. return "";
  128. }
  129. }
  130. mo.Dispose();
  131. }
  132. return macAddress.Replace(":", "");
  133. }
  134. /// <summary>
  135. /// Uses the DllImport : NetServerEnum with all its required parameters
  136. /// (see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/netserverenum.asp
  137. /// for full details or method signature) to retrieve a list of domain SV_TYPE_WORKSTATION
  138. /// and SV_TYPE_SERVER PC's
  139. /// </summary>
  140. /// <returns>Arraylist that represents all the SV_TYPE_WORKSTATION and SV_TYPE_SERVER
  141. /// PC's in the Domain</returns>
  142. public IEnumerable<string> GetNetworkDevices()
  143. {
  144. //local fields
  145. const int MAX_PREFERRED_LENGTH = -1;
  146. var SV_TYPE_WORKSTATION = 1;
  147. var SV_TYPE_SERVER = 2;
  148. var buffer = IntPtr.Zero;
  149. var tmpBuffer = IntPtr.Zero;
  150. var entriesRead = 0;
  151. var totalEntries = 0;
  152. var resHandle = 0;
  153. var sizeofINFO = Marshal.SizeOf(typeof(_SERVER_INFO_100));
  154. try
  155. {
  156. //call the DllImport : NetServerEnum with all its required parameters
  157. //see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/netserverenum.asp
  158. //for full details of method signature
  159. var ret = NativeMethods.NetServerEnum(null, 100, ref buffer, MAX_PREFERRED_LENGTH, out entriesRead, out totalEntries, SV_TYPE_WORKSTATION | SV_TYPE_SERVER, null, out resHandle);
  160. //if the returned with a NERR_Success (C++ term), =0 for C#
  161. if (ret == 0)
  162. {
  163. //loop through all SV_TYPE_WORKSTATION and SV_TYPE_SERVER PC's
  164. for (var i = 0; i < totalEntries; i++)
  165. {
  166. //get pointer to, Pointer to the buffer that received the data from
  167. //the call to NetServerEnum. Must ensure to use correct size of
  168. //STRUCTURE to ensure correct location in memory is pointed to
  169. tmpBuffer = new IntPtr((int)buffer + (i * sizeofINFO));
  170. //Have now got a pointer to the list of SV_TYPE_WORKSTATION and
  171. //SV_TYPE_SERVER PC's, which is unmanaged memory
  172. //Needs to Marshal data from an unmanaged block of memory to a
  173. //managed object, again using STRUCTURE to ensure the correct data
  174. //is marshalled
  175. var svrInfo = (_SERVER_INFO_100)Marshal.PtrToStructure(tmpBuffer, typeof(_SERVER_INFO_100));
  176. //add the PC names to the ArrayList
  177. if (!string.IsNullOrEmpty(svrInfo.sv100_name))
  178. {
  179. yield return svrInfo.sv100_name;
  180. }
  181. }
  182. }
  183. }
  184. finally
  185. {
  186. //The NetApiBufferFree function frees
  187. //the memory that the NetApiBufferAllocate function allocates
  188. NativeMethods.NetApiBufferFree(buffer);
  189. }
  190. }
  191. /// <summary>
  192. /// Gets the network shares.
  193. /// </summary>
  194. /// <param name="path">The path.</param>
  195. /// <returns>IEnumerable{NetworkShare}.</returns>
  196. public IEnumerable<NetworkShare> GetNetworkShares(string path)
  197. {
  198. return new ShareCollection(path).OfType<Share>().Select(ToNetworkShare);
  199. }
  200. /// <summary>
  201. /// To the network share.
  202. /// </summary>
  203. /// <param name="share">The share.</param>
  204. /// <returns>NetworkShare.</returns>
  205. private NetworkShare ToNetworkShare(Share share)
  206. {
  207. return new NetworkShare
  208. {
  209. Name = share.NetName,
  210. Path = share.Path,
  211. Remark = share.Remark,
  212. Server = share.Server,
  213. ShareType = ToNetworkShareType(share.ShareType)
  214. };
  215. }
  216. /// <summary>
  217. /// To the type of the network share.
  218. /// </summary>
  219. /// <param name="shareType">Type of the share.</param>
  220. /// <returns>NetworkShareType.</returns>
  221. /// <exception cref="System.ArgumentException">Unknown share type</exception>
  222. private NetworkShareType ToNetworkShareType(ShareType shareType)
  223. {
  224. if (shareType.HasFlag(ShareType.Special))
  225. {
  226. return NetworkShareType.Special;
  227. }
  228. if (shareType.HasFlag(ShareType.Device))
  229. {
  230. return NetworkShareType.Device;
  231. }
  232. if (shareType.HasFlag(ShareType.Disk))
  233. {
  234. return NetworkShareType.Disk;
  235. }
  236. if (shareType.HasFlag(ShareType.IPC))
  237. {
  238. return NetworkShareType.Ipc;
  239. }
  240. if (shareType.HasFlag(ShareType.Printer))
  241. {
  242. return NetworkShareType.Printer;
  243. }
  244. throw new ArgumentException("Unknown share type");
  245. }
  246. /// <summary>
  247. /// Parses the specified endpointstring.
  248. /// </summary>
  249. /// <param name="endpointstring">The endpointstring.</param>
  250. /// <returns>IPEndPoint.</returns>
  251. public IPEndPoint Parse(string endpointstring)
  252. {
  253. return Parse(endpointstring, -1);
  254. }
  255. /// <summary>
  256. /// Parses the specified endpointstring.
  257. /// </summary>
  258. /// <param name="endpointstring">The endpointstring.</param>
  259. /// <param name="defaultport">The defaultport.</param>
  260. /// <returns>IPEndPoint.</returns>
  261. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  262. /// <exception cref="System.FormatException"></exception>
  263. private static IPEndPoint Parse(string endpointstring, int defaultport)
  264. {
  265. if (string.IsNullOrEmpty(endpointstring)
  266. || endpointstring.Trim().Length == 0)
  267. {
  268. throw new ArgumentException("Endpoint descriptor may not be empty.");
  269. }
  270. if (defaultport != -1 &&
  271. (defaultport < IPEndPoint.MinPort
  272. || defaultport > IPEndPoint.MaxPort))
  273. {
  274. throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport));
  275. }
  276. string[] values = endpointstring.Split(new char[] { ':' });
  277. IPAddress ipaddy;
  278. int port = -1;
  279. //check if we have an IPv6 or ports
  280. if (values.Length <= 2) // ipv4 or hostname
  281. {
  282. port = values.Length == 1 ? defaultport : GetPort(values[1]);
  283. //try to use the address as IPv4, otherwise get hostname
  284. if (!IPAddress.TryParse(values[0], out ipaddy))
  285. ipaddy = GetIPfromHost(values[0]);
  286. }
  287. else if (values.Length > 2) //ipv6
  288. {
  289. //could [a:b:c]:d
  290. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  291. {
  292. string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray());
  293. ipaddy = IPAddress.Parse(ipaddressstring);
  294. port = GetPort(values[values.Length - 1]);
  295. }
  296. else //[a:b:c] or a:b:c
  297. {
  298. ipaddy = IPAddress.Parse(endpointstring);
  299. port = defaultport;
  300. }
  301. }
  302. else
  303. {
  304. throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  305. }
  306. if (port == -1)
  307. throw new ArgumentException(string.Format("No port specified: '{0}'", endpointstring));
  308. return new IPEndPoint(ipaddy, port);
  309. }
  310. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  311. /// <summary>
  312. /// Gets the port.
  313. /// </summary>
  314. /// <param name="p">The p.</param>
  315. /// <returns>System.Int32.</returns>
  316. /// <exception cref="System.FormatException"></exception>
  317. private static int GetPort(string p)
  318. {
  319. int port;
  320. if (!int.TryParse(p, out port)
  321. || port < IPEndPoint.MinPort
  322. || port > IPEndPoint.MaxPort)
  323. {
  324. throw new FormatException(string.Format("Invalid end point port '{0}'", p));
  325. }
  326. return port;
  327. }
  328. /// <summary>
  329. /// Gets the I pfrom host.
  330. /// </summary>
  331. /// <param name="p">The p.</param>
  332. /// <returns>IPAddress.</returns>
  333. /// <exception cref="System.ArgumentException"></exception>
  334. private static IPAddress GetIPfromHost(string p)
  335. {
  336. var hosts = Dns.GetHostAddresses(p);
  337. if (hosts == null || hosts.Length == 0)
  338. throw new ArgumentException(string.Format("Host not found: {0}", p));
  339. return hosts[0];
  340. }
  341. }
  342. }