NetworkManager.cs 14 KB

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