NetworkManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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.Linq;
  7. using System.Management;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Runtime.InteropServices;
  11. namespace MediaBrowser.Networking.Management
  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.FirstOrDefault(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. switch (shareType)
  224. {
  225. case ShareType.Device:
  226. return NetworkShareType.Device;
  227. case ShareType.Disk :
  228. return NetworkShareType.Disk;
  229. case ShareType.IPC :
  230. return NetworkShareType.Ipc;
  231. case ShareType.Printer :
  232. return NetworkShareType.Printer;
  233. case ShareType.Special:
  234. return NetworkShareType.Special;
  235. default:
  236. throw new ArgumentException("Unknown share type");
  237. }
  238. }
  239. /// <summary>
  240. /// Parses the specified endpointstring.
  241. /// </summary>
  242. /// <param name="endpointstring">The endpointstring.</param>
  243. /// <returns>IPEndPoint.</returns>
  244. public IPEndPoint Parse(string endpointstring)
  245. {
  246. return Parse(endpointstring, -1);
  247. }
  248. /// <summary>
  249. /// Parses the specified endpointstring.
  250. /// </summary>
  251. /// <param name="endpointstring">The endpointstring.</param>
  252. /// <param name="defaultport">The defaultport.</param>
  253. /// <returns>IPEndPoint.</returns>
  254. /// <exception cref="System.ArgumentException">Endpoint descriptor may not be empty.</exception>
  255. /// <exception cref="System.FormatException"></exception>
  256. private static IPEndPoint Parse(string endpointstring, int defaultport)
  257. {
  258. if (string.IsNullOrEmpty(endpointstring)
  259. || endpointstring.Trim().Length == 0)
  260. {
  261. throw new ArgumentException("Endpoint descriptor may not be empty.");
  262. }
  263. if (defaultport != -1 &&
  264. (defaultport < IPEndPoint.MinPort
  265. || defaultport > IPEndPoint.MaxPort))
  266. {
  267. throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport));
  268. }
  269. string[] values = endpointstring.Split(new char[] { ':' });
  270. IPAddress ipaddy;
  271. int port = -1;
  272. //check if we have an IPv6 or ports
  273. if (values.Length <= 2) // ipv4 or hostname
  274. {
  275. if (values.Length == 1)
  276. //no port is specified, default
  277. port = defaultport;
  278. else
  279. port = GetPort(values[1]);
  280. //try to use the address as IPv4, otherwise get hostname
  281. if (!IPAddress.TryParse(values[0], out ipaddy))
  282. ipaddy = GetIPfromHost(values[0]);
  283. }
  284. else if (values.Length > 2) //ipv6
  285. {
  286. //could [a:b:c]:d
  287. if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
  288. {
  289. string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray());
  290. ipaddy = IPAddress.Parse(ipaddressstring);
  291. port = GetPort(values[values.Length - 1]);
  292. }
  293. else //[a:b:c] or a:b:c
  294. {
  295. ipaddy = IPAddress.Parse(endpointstring);
  296. port = defaultport;
  297. }
  298. }
  299. else
  300. {
  301. throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
  302. }
  303. if (port == -1)
  304. throw new ArgumentException(string.Format("No port specified: '{0}'", endpointstring));
  305. return new IPEndPoint(ipaddy, port);
  306. }
  307. /// <summary>
  308. /// Gets the port.
  309. /// </summary>
  310. /// <param name="p">The p.</param>
  311. /// <returns>System.Int32.</returns>
  312. /// <exception cref="System.FormatException"></exception>
  313. private static int GetPort(string p)
  314. {
  315. int port;
  316. if (!int.TryParse(p, out port)
  317. || port < IPEndPoint.MinPort
  318. || port > IPEndPoint.MaxPort)
  319. {
  320. throw new FormatException(string.Format("Invalid end point port '{0}'", p));
  321. }
  322. return port;
  323. }
  324. /// <summary>
  325. /// Gets the I pfrom host.
  326. /// </summary>
  327. /// <param name="p">The p.</param>
  328. /// <returns>IPAddress.</returns>
  329. /// <exception cref="System.ArgumentException"></exception>
  330. private static IPAddress GetIPfromHost(string p)
  331. {
  332. var hosts = Dns.GetHostAddresses(p);
  333. if (hosts == null || hosts.Length == 0)
  334. throw new ArgumentException(string.Format("Host not found: {0}", p));
  335. return hosts[0];
  336. }
  337. }
  338. }