WlanClient.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Runtime.InteropServices;
  5. using System.Net.NetworkInformation;
  6. using System.Threading;
  7. using System.Text;
  8. namespace Azylee.Core.NetUtils.WifiManUtils
  9. {
  10. /// <summary>
  11. /// Represents a client to the Zeroconf (Native Wifi) service.
  12. /// </summary>
  13. /// <remarks>
  14. /// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance
  15. /// of this class.
  16. /// </remarks>
  17. public class WlanClient : IDisposable
  18. {
  19. /// <summary>
  20. /// Represents a Wifi network interface.
  21. /// </summary>
  22. public class WlanInterface
  23. {
  24. private readonly WlanClient client;
  25. private Wlan.WlanInterfaceInfo info;
  26. #region Events
  27. /// <summary>
  28. /// Represents a method that will handle <see cref="WlanNotification"/> events.
  29. /// </summary>
  30. /// <param name="notifyData">The notification data.</param>
  31. public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData);
  32. /// <summary>
  33. /// Represents a method that will handle <see cref="WlanConnectionNotification"/> events.
  34. /// </summary>
  35. /// <param name="notifyData">The notification data.</param>
  36. /// <param name="connNotifyData">The notification data.</param>
  37. public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData);
  38. /// <summary>
  39. /// Represents a method that will handle <see cref="WlanReasonNotification"/> events.
  40. /// </summary>
  41. /// <param name="notifyData">The notification data.</param>
  42. /// <param name="reasonCode">The reason code.</param>
  43. public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode);
  44. /// <summary>
  45. /// Occurs when an event of any kind occurs on a WLAN interface.
  46. /// </summary>
  47. public event WlanNotificationEventHandler WlanNotification;
  48. /// <summary>
  49. /// Occurs when a WLAN interface changes connection state.
  50. /// </summary>
  51. public event WlanConnectionNotificationEventHandler WlanConnectionNotification;
  52. /// <summary>
  53. /// Occurs when a WLAN operation fails due to some reason.
  54. /// </summary>
  55. public event WlanReasonNotificationEventHandler WlanReasonNotification;
  56. #endregion
  57. #region Event queue
  58. private bool queueEvents;
  59. private readonly AutoResetEvent eventQueueFilled = new AutoResetEvent(false);
  60. private readonly Queue<object> eventQueue = new Queue<object>();
  61. private struct WlanConnectionNotificationEventData
  62. {
  63. public Wlan.WlanNotificationData notifyData;
  64. public Wlan.WlanConnectionNotificationData connNotifyData;
  65. }
  66. private struct WlanReasonNotificationData
  67. {
  68. public Wlan.WlanNotificationData notifyData;
  69. public Wlan.WlanReasonCode reasonCode;
  70. }
  71. #endregion
  72. internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
  73. {
  74. this.client = client;
  75. this.info = info;
  76. }
  77. /// <summary>
  78. /// Sets a parameter of the interface whose data type is <see cref="int"/>.
  79. /// </summary>
  80. /// <param name="opCode">The opcode of the parameter.</param>
  81. /// <param name="value">The value to set.</param>
  82. private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
  83. {
  84. IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
  85. Marshal.WriteInt32(valuePtr, value);
  86. try
  87. {
  88. Wlan.ThrowIfError(
  89. Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
  90. }
  91. finally
  92. {
  93. Marshal.FreeHGlobal(valuePtr);
  94. }
  95. }
  96. /// <summary>
  97. /// Gets a parameter of the interface whose data type is <see cref="int"/>.
  98. /// </summary>
  99. /// <param name="opCode">The opcode of the parameter.</param>
  100. /// <returns>The integer value.</returns>
  101. private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
  102. {
  103. IntPtr valuePtr;
  104. int valueSize;
  105. Wlan.WlanOpcodeValueType opcodeValueType;
  106. Wlan.ThrowIfError(
  107. Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
  108. try
  109. {
  110. return Marshal.ReadInt32(valuePtr);
  111. }
  112. finally
  113. {
  114. Wlan.WlanFreeMemory(valuePtr);
  115. }
  116. }
  117. /// <summary>
  118. /// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured.
  119. /// </summary>
  120. /// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value>
  121. public bool Autoconf
  122. {
  123. get
  124. {
  125. return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0;
  126. }
  127. set
  128. {
  129. SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0);
  130. }
  131. }
  132. /// <summary>
  133. /// Gets or sets the BSS type for the indicated interface.
  134. /// </summary>
  135. /// <value>The type of the BSS.</value>
  136. public Wlan.Dot11BssType BssType
  137. {
  138. get
  139. {
  140. return (Wlan.Dot11BssType)GetInterfaceInt(Wlan.WlanIntfOpcode.BssType);
  141. }
  142. set
  143. {
  144. SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value);
  145. }
  146. }
  147. /// <summary>
  148. /// Gets the state of the interface.
  149. /// </summary>
  150. /// <value>The state of the interface.</value>
  151. public Wlan.WlanInterfaceState InterfaceState
  152. {
  153. get
  154. {
  155. return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState);
  156. }
  157. }
  158. /// <summary>
  159. /// Gets the channel.
  160. /// </summary>
  161. /// <value>The channel.</value>
  162. /// <remarks>Not supported on Windows XP SP2.</remarks>
  163. public int Channel
  164. {
  165. get
  166. {
  167. return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber);
  168. }
  169. }
  170. /// <summary>
  171. /// Gets the RSSI.
  172. /// </summary>
  173. /// <value>The RSSI.</value>
  174. /// <remarks>Not supported on Windows XP SP2.</remarks>
  175. public int RSSI
  176. {
  177. get
  178. {
  179. return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI);
  180. }
  181. }
  182. /// <summary>
  183. /// Gets the radio state.
  184. /// </summary>
  185. /// <value>The radio state.</value>
  186. /// <remarks>Not supported on Windows XP.</remarks>
  187. public Wlan.WlanRadioState RadioState
  188. {
  189. get
  190. {
  191. int valueSize;
  192. IntPtr valuePtr;
  193. Wlan.WlanOpcodeValueType opcodeValueType;
  194. Wlan.ThrowIfError(
  195. Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.RadioState, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
  196. try
  197. {
  198. return (Wlan.WlanRadioState)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanRadioState));
  199. }
  200. finally
  201. {
  202. Wlan.WlanFreeMemory(valuePtr);
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Gets the current operation mode.
  208. /// </summary>
  209. /// <value>The current operation mode.</value>
  210. /// <remarks>Not supported on Windows XP SP2.</remarks>
  211. public Wlan.Dot11OperationMode CurrentOperationMode
  212. {
  213. get
  214. {
  215. return (Wlan.Dot11OperationMode)GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode);
  216. }
  217. }
  218. /// <summary>
  219. /// Gets the attributes of the current connection.
  220. /// </summary>
  221. /// <value>The current connection attributes.</value>
  222. /// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception>
  223. public Wlan.WlanConnectionAttributes CurrentConnection
  224. {
  225. get
  226. {
  227. int valueSize;
  228. IntPtr valuePtr;
  229. Wlan.WlanOpcodeValueType opcodeValueType;
  230. Wlan.ThrowIfError(
  231. Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
  232. try
  233. {
  234. return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
  235. }
  236. finally
  237. {
  238. Wlan.WlanFreeMemory(valuePtr);
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Requests a scan for available networks.
  244. /// </summary>
  245. /// <remarks>
  246. /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  247. /// </remarks>
  248. public void Scan()
  249. {
  250. Wlan.ThrowIfError(
  251. Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
  252. }
  253. /// <summary>
  254. /// Converts a pointer to a available networks list (header + entries) to an array of available network entries.
  255. /// </summary>
  256. /// <param name="availNetListPtr">A pointer to an available networks list's header.</param>
  257. /// <returns>An array of available network entries.</returns>
  258. private static Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr)
  259. {
  260. Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader));
  261. long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader));
  262. Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems];
  263. for (int i = 0; i < availNetListHeader.numberOfItems; ++i)
  264. {
  265. availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork));
  266. availNets[i].profileName = WlanTool.GetStringForSSID(availNets[i].dot11Ssid);
  267. availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork));
  268. }
  269. return availNets;
  270. }
  271. /// <summary>
  272. /// Retrieves the list of available networks.
  273. /// </summary>
  274. /// <param name="flags">Controls the type of networks returned.</param>
  275. /// <returns>A list of the available networks.</returns>
  276. public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
  277. {
  278. IntPtr availNetListPtr;
  279. Wlan.ThrowIfError(
  280. Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
  281. try
  282. {
  283. return ConvertAvailableNetworkListPtr(availNetListPtr);
  284. }
  285. finally
  286. {
  287. Wlan.WlanFreeMemory(availNetListPtr);
  288. }
  289. }
  290. /// <summary>
  291. /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries.
  292. /// </summary>
  293. /// <param name="bssListPtr">A pointer to a BSS list's header.</param>
  294. /// <returns>An array of BSS entries.</returns>
  295. private static Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr)
  296. {
  297. Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader));
  298. long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader));
  299. Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems];
  300. for (int i = 0; i < bssListHeader.numberOfItems; ++i)
  301. {
  302. bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry));
  303. bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry));
  304. }
  305. return bssEntries;
  306. }
  307. /// <summary>
  308. /// Retrieves the basic service sets (BSS) list of all available networks.
  309. /// </summary>
  310. public Wlan.WlanBssEntry[] GetNetworkBssList()
  311. {
  312. IntPtr bssListPtr;
  313. Wlan.ThrowIfError(
  314. Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
  315. try
  316. {
  317. return ConvertBssListPtr(bssListPtr);
  318. }
  319. finally
  320. {
  321. Wlan.WlanFreeMemory(bssListPtr);
  322. }
  323. }
  324. /// <summary>
  325. /// Retrieves the basic service sets (BSS) list of the specified network.
  326. /// </summary>
  327. /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
  328. /// <param name="bssType">Indicates the BSS type of the network.</param>
  329. /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
  330. public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
  331. {
  332. IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
  333. Marshal.StructureToPtr(ssid, ssidPtr, false);
  334. try
  335. {
  336. IntPtr bssListPtr;
  337. Wlan.ThrowIfError(
  338. Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
  339. try
  340. {
  341. return ConvertBssListPtr(bssListPtr);
  342. }
  343. finally
  344. {
  345. Wlan.WlanFreeMemory(bssListPtr);
  346. }
  347. }
  348. finally
  349. {
  350. Marshal.FreeHGlobal(ssidPtr);
  351. }
  352. }
  353. /// <summary>
  354. /// Connects to a network defined by a connection parameters structure.
  355. /// </summary>
  356. /// <param name="connectionParams">The connection paramters.</param>
  357. protected void Connect(Wlan.WlanConnectionParameters connectionParams)
  358. {
  359. Wlan.ThrowIfError(
  360. Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
  361. }
  362. /// <summary>
  363. /// Requests a connection (association) to the specified wireless network.
  364. /// </summary>
  365. /// <remarks>
  366. /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  367. /// </remarks>
  368. public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
  369. {
  370. Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
  371. connectionParams.wlanConnectionMode = connectionMode;
  372. connectionParams.profile = profile;
  373. connectionParams.dot11BssType = bssType;
  374. connectionParams.flags = 0;
  375. Connect(connectionParams);
  376. }
  377. /// <summary>
  378. /// Connects (associates) to the specified wireless network, returning either on a success to connect
  379. /// or a failure.
  380. /// </summary>
  381. /// <param name="connectionMode"></param>
  382. /// <param name="bssType"></param>
  383. /// <param name="profile"></param>
  384. /// <param name="connectTimeout"></param>
  385. /// <returns></returns>
  386. public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
  387. {
  388. queueEvents = true;
  389. try
  390. {
  391. Connect(connectionMode, bssType, profile);
  392. while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
  393. {
  394. lock (eventQueue)
  395. {
  396. while (eventQueue.Count != 0)
  397. {
  398. object e = eventQueue.Dequeue();
  399. if (e is WlanConnectionNotificationEventData)
  400. {
  401. WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
  402. // Check if the conditions are good to indicate either success or failure.
  403. if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
  404. {
  405. switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
  406. {
  407. case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
  408. if (wlanConnectionData.connNotifyData.profileName == profile)
  409. return true;
  410. break;
  411. }
  412. }
  413. break;
  414. }
  415. }
  416. }
  417. }
  418. }
  419. finally
  420. {
  421. queueEvents = false;
  422. eventQueue.Clear();
  423. }
  424. return false; // timeout expired and no "connection complete"
  425. }
  426. /// <summary>
  427. /// Connects to the specified wireless network.
  428. /// </summary>
  429. /// <remarks>
  430. /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  431. /// </remarks>
  432. public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
  433. {
  434. Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
  435. connectionParams.wlanConnectionMode = connectionMode;
  436. connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
  437. Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
  438. connectionParams.dot11BssType = bssType;
  439. connectionParams.flags = flags;
  440. Connect(connectionParams);
  441. Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
  442. Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
  443. }
  444. /// <summary>
  445. /// Deletes a profile.
  446. /// </summary>
  447. /// <param name="profileName">
  448. /// The name of the profile to be deleted. Profile names are case-sensitive.
  449. /// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>.
  450. /// </param>
  451. public void DeleteProfile(string profileName)
  452. {
  453. Wlan.ThrowIfError(
  454. Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
  455. }
  456. /// <summary>
  457. /// Sets the profile.
  458. /// </summary>
  459. /// <param name="flags">The flags to set on the profile.</param>
  460. /// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param>
  461. /// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param>
  462. /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
  463. public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
  464. {
  465. Wlan.WlanReasonCode reasonCode;
  466. Wlan.ThrowIfError(
  467. Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode));
  468. return reasonCode;
  469. }
  470. /// <summary>
  471. /// Gets the profile's XML specification.
  472. /// </summary>
  473. /// <param name="profileName">The name of the profile.</param>
  474. /// <returns>The XML document.</returns>
  475. public string GetProfileXml(string profileName)
  476. {
  477. IntPtr profileXmlPtr;
  478. Wlan.WlanProfileFlags flags;
  479. Wlan.WlanAccess access;
  480. Wlan.ThrowIfError(
  481. Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags,
  482. out access));
  483. try
  484. {
  485. return Marshal.PtrToStringUni(profileXmlPtr);
  486. }
  487. finally
  488. {
  489. Wlan.WlanFreeMemory(profileXmlPtr);
  490. }
  491. }
  492. /// <summary>
  493. /// Gets the information of all profiles on this interface.
  494. /// </summary>
  495. /// <returns>The profiles information.</returns>
  496. public Wlan.WlanProfileInfo[] GetProfiles()
  497. {
  498. IntPtr profileListPtr;
  499. Wlan.ThrowIfError(
  500. Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
  501. try
  502. {
  503. Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
  504. Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
  505. long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
  506. for (int i = 0; i < header.numberOfItems; ++i)
  507. {
  508. Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo));
  509. profileInfos[i] = profileInfo;
  510. profileListIterator += Marshal.SizeOf(profileInfo);
  511. }
  512. return profileInfos;
  513. }
  514. finally
  515. {
  516. Wlan.WlanFreeMemory(profileListPtr);
  517. }
  518. }
  519. internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
  520. {
  521. if (WlanConnectionNotification != null)
  522. WlanConnectionNotification(notifyData, connNotifyData);
  523. if (queueEvents)
  524. {
  525. WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData();
  526. queuedEvent.notifyData = notifyData;
  527. queuedEvent.connNotifyData = connNotifyData;
  528. EnqueueEvent(queuedEvent);
  529. }
  530. }
  531. internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode)
  532. {
  533. if (WlanReasonNotification != null)
  534. WlanReasonNotification(notifyData, reasonCode);
  535. if (queueEvents)
  536. {
  537. WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData();
  538. queuedEvent.notifyData = notifyData;
  539. queuedEvent.reasonCode = reasonCode;
  540. EnqueueEvent(queuedEvent);
  541. }
  542. }
  543. internal void OnWlanNotification(Wlan.WlanNotificationData notifyData)
  544. {
  545. if (WlanNotification != null)
  546. WlanNotification(notifyData);
  547. }
  548. /// <summary>
  549. /// Enqueues a notification event to be processed serially.
  550. /// </summary>
  551. private void EnqueueEvent(object queuedEvent)
  552. {
  553. lock (eventQueue)
  554. eventQueue.Enqueue(queuedEvent);
  555. eventQueueFilled.Set();
  556. }
  557. /// <summary>
  558. /// Gets the network interface of this wireless interface.
  559. /// </summary>
  560. /// <remarks>
  561. /// The network interface allows querying of generic network properties such as the interface's IP address.
  562. /// </remarks>
  563. public NetworkInterface NetworkInterface
  564. {
  565. get
  566. {
  567. // Do not cache the NetworkInterface; We need it fresh
  568. // each time cause otherwise it caches the IP information.
  569. foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces())
  570. {
  571. Guid netIfaceGuid = new Guid(netIface.Id);
  572. if (netIfaceGuid.Equals(info.interfaceGuid))
  573. {
  574. return netIface;
  575. }
  576. }
  577. return null;
  578. }
  579. }
  580. /// <summary>
  581. /// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value).
  582. /// </summary>
  583. public Guid InterfaceGuid
  584. {
  585. get { return info.interfaceGuid; }
  586. }
  587. /// <summary>
  588. /// The description of the interface.
  589. /// This is a user-immutable string containing the vendor and model name of the adapter.
  590. /// </summary>
  591. public string InterfaceDescription
  592. {
  593. get { return info.interfaceDescription; }
  594. }
  595. /// <summary>
  596. /// The friendly name given to the interface by the user (e.g. "Local Area Network Connection").
  597. /// </summary>
  598. public string InterfaceName
  599. {
  600. get { return NetworkInterface.Name; }
  601. }
  602. }
  603. private IntPtr clientHandle;
  604. private uint negotiatedVersion;
  605. private readonly Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback;
  606. private readonly Dictionary<Guid, WlanInterface> ifaces = new Dictionary<Guid, WlanInterface>();
  607. /// <summary>
  608. /// Creates a new instance of a Native Wifi service client.
  609. /// </summary>
  610. public WlanClient()
  611. {
  612. Wlan.ThrowIfError(
  613. Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
  614. try
  615. {
  616. Wlan.WlanNotificationSource prevSrc;
  617. wlanNotificationCallback = OnWlanNotification;
  618. Wlan.ThrowIfError(
  619. Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
  620. }
  621. catch
  622. {
  623. Close();
  624. throw;
  625. }
  626. }
  627. void IDisposable.Dispose()
  628. {
  629. GC.SuppressFinalize(this);
  630. Close();
  631. }
  632. ~WlanClient()
  633. {
  634. Close();
  635. }
  636. /// <summary>
  637. /// Closes the handle.
  638. /// </summary>
  639. private void Close()
  640. {
  641. if (clientHandle != IntPtr.Zero)
  642. {
  643. Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
  644. clientHandle = IntPtr.Zero;
  645. }
  646. }
  647. private static Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
  648. {
  649. int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
  650. if (notifyData.dataSize < expectedSize)
  651. return null;
  652. Wlan.WlanConnectionNotificationData connNotifyData =
  653. (Wlan.WlanConnectionNotificationData)
  654. Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
  655. if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
  656. {
  657. IntPtr profileXmlPtr = new IntPtr(
  658. notifyData.dataPtr.ToInt64() +
  659. Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
  660. connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
  661. }
  662. return connNotifyData;
  663. }
  664. private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
  665. {
  666. WlanInterface wlanIface;
  667. ifaces.TryGetValue(notifyData.interfaceGuid, out wlanIface);
  668. switch (notifyData.notificationSource)
  669. {
  670. case Wlan.WlanNotificationSource.ACM:
  671. switch ((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
  672. {
  673. case Wlan.WlanNotificationCodeAcm.ConnectionStart:
  674. case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
  675. case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
  676. case Wlan.WlanNotificationCodeAcm.Disconnecting:
  677. case Wlan.WlanNotificationCodeAcm.Disconnected:
  678. Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
  679. if (connNotifyData.HasValue)
  680. if (wlanIface != null)
  681. wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
  682. break;
  683. case Wlan.WlanNotificationCodeAcm.ScanFail:
  684. {
  685. int expectedSize = Marshal.SizeOf(typeof(int));
  686. if (notifyData.dataSize >= expectedSize)
  687. {
  688. Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
  689. if (wlanIface != null)
  690. wlanIface.OnWlanReason(notifyData, reasonCode);
  691. }
  692. }
  693. break;
  694. }
  695. break;
  696. case Wlan.WlanNotificationSource.MSM:
  697. switch ((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
  698. {
  699. case Wlan.WlanNotificationCodeMsm.Associating:
  700. case Wlan.WlanNotificationCodeMsm.Associated:
  701. case Wlan.WlanNotificationCodeMsm.Authenticating:
  702. case Wlan.WlanNotificationCodeMsm.Connected:
  703. case Wlan.WlanNotificationCodeMsm.RoamingStart:
  704. case Wlan.WlanNotificationCodeMsm.RoamingEnd:
  705. case Wlan.WlanNotificationCodeMsm.Disassociating:
  706. case Wlan.WlanNotificationCodeMsm.Disconnected:
  707. case Wlan.WlanNotificationCodeMsm.PeerJoin:
  708. case Wlan.WlanNotificationCodeMsm.PeerLeave:
  709. case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
  710. Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
  711. if (connNotifyData.HasValue)
  712. if (wlanIface != null)
  713. wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
  714. break;
  715. }
  716. break;
  717. }
  718. if (wlanIface != null)
  719. wlanIface.OnWlanNotification(notifyData);
  720. }
  721. /// <summary>
  722. /// Gets the WLAN interfaces.
  723. /// </summary>
  724. /// <value>The WLAN interfaces.</value>
  725. public WlanInterface[] Interfaces
  726. {
  727. get
  728. {
  729. IntPtr ifaceList;
  730. Wlan.ThrowIfError(
  731. Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList));
  732. try
  733. {
  734. Wlan.WlanInterfaceInfoListHeader header =
  735. (Wlan.WlanInterfaceInfoListHeader)Marshal.PtrToStructure(ifaceList, typeof(Wlan.WlanInterfaceInfoListHeader));
  736. Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header);
  737. WlanInterface[] interfaces = new WlanInterface[header.numberOfItems];
  738. List<Guid> currentIfaceGuids = new List<Guid>();
  739. for (int i = 0; i < header.numberOfItems; ++i)
  740. {
  741. Wlan.WlanInterfaceInfo info =
  742. (Wlan.WlanInterfaceInfo)Marshal.PtrToStructure(new IntPtr(listIterator), typeof(Wlan.WlanInterfaceInfo));
  743. listIterator += Marshal.SizeOf(info);
  744. currentIfaceGuids.Add(info.interfaceGuid);
  745. WlanInterface wlanIface;
  746. if (!ifaces.TryGetValue(info.interfaceGuid, out wlanIface))
  747. {
  748. wlanIface = new WlanInterface(this, info);
  749. ifaces[info.interfaceGuid] = wlanIface;
  750. }
  751. interfaces[i] = wlanIface;
  752. }
  753. // Remove stale interfaces
  754. Queue<Guid> deadIfacesGuids = new Queue<Guid>();
  755. foreach (Guid ifaceGuid in ifaces.Keys)
  756. {
  757. if (!currentIfaceGuids.Contains(ifaceGuid))
  758. deadIfacesGuids.Enqueue(ifaceGuid);
  759. }
  760. while (deadIfacesGuids.Count != 0)
  761. {
  762. Guid deadIfaceGuid = deadIfacesGuids.Dequeue();
  763. ifaces.Remove(deadIfaceGuid);
  764. }
  765. return interfaces;
  766. }
  767. finally
  768. {
  769. Wlan.WlanFreeMemory(ifaceList);
  770. }
  771. }
  772. }
  773. /// <summary>
  774. /// Gets a string that describes a specified reason code.
  775. /// </summary>
  776. /// <param name="reasonCode">The reason code.</param>
  777. /// <returns>The string.</returns>
  778. public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
  779. {
  780. StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
  781. Wlan.ThrowIfError(
  782. Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
  783. return sb.ToString();
  784. }
  785. }
  786. }