home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 February / maximum-cd-2011-02.iso / DiscContents / ConnectifyInstaller.exe / source / ManagedWifi / WlanApi.cs < prev   
Encoding:
Text File  |  2010-09-17  |  45.6 KB  |  1,152 lines

  1. /** HostedNetwork calls added by Connectify.  2009, 2010 */
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Runtime.InteropServices;
  6. using System.Net.NetworkInformation;
  7. using System.Threading;
  8. using System.Text;
  9.  
  10. namespace NativeWifi
  11. {
  12.     /// <summary>
  13.     /// Represents a client to the Zeroconf (Native Wifi) service.
  14.     /// </summary>
  15.     /// <remarks>
  16.     /// This class is the entrypoint to Native Wifi management. To manage Wi-Fi settings, create an instance
  17.     /// of this class.
  18.     /// </remarks>
  19.     public class WlanClient
  20.     {
  21.         /// <summary>
  22.         /// Represents a Wifi network interface.
  23.         /// </summary>
  24.         public class WlanInterface
  25.         {
  26.             private WlanClient client;
  27.             private Wlan.WlanInterfaceInfo info;
  28.  
  29.             #region Events
  30.             /// <summary>
  31.             /// Represents a method that will handle <see cref="WlanNotification"/> events.
  32.             /// </summary>
  33.             /// <param name="notifyData">The notification data.</param>
  34.             public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData);
  35.  
  36.             /// <summary>
  37.             /// Represents a method that will handle <see cref="WlanConnectionNotification"/> events.
  38.             /// </summary>
  39.             /// <param name="notifyData">The notification data.</param>
  40.             /// <param name="connNotifyData">The notification data.</param>
  41.             public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData);
  42.  
  43.             /// <summary>
  44.             /// Represents a method that will handle <see cref="WlanReasonNotification"/> events.
  45.             /// </summary>
  46.             /// <param name="notifyData">The notification data.</param>
  47.             /// <param name="reasonCode">The reason code.</param>
  48.             public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode);
  49.  
  50.             /// <summary>
  51.             /// Occurs when an event of any kind occurs on a WLAN interface.
  52.             /// </summary>
  53.             public event WlanNotificationEventHandler WlanNotification;
  54.  
  55.             /// <summary>
  56.             /// Occurs when a WLAN interface changes connection state.
  57.             /// </summary>
  58.             public event WlanConnectionNotificationEventHandler WlanConnectionNotification;
  59.  
  60.             /// <summary>
  61.             /// Occurs when a WLAN operation fails due to some reason.
  62.             /// </summary>
  63.             public event WlanReasonNotificationEventHandler WlanReasonNotification;
  64.  
  65.             #endregion
  66.  
  67.             #region Event queue
  68.             private bool queueEvents;
  69.             private AutoResetEvent eventQueueFilled = new AutoResetEvent(false);
  70.             private Queue<object> eventQueue = new Queue<object>();
  71.  
  72.             private struct WlanConnectionNotificationEventData
  73.             {
  74.                 public Wlan.WlanNotificationData notifyData;
  75.                 public Wlan.WlanConnectionNotificationData connNotifyData;
  76.             }
  77.             private struct WlanReasonNotificationData
  78.             {
  79.                 public Wlan.WlanNotificationData notifyData;
  80.                 public Wlan.WlanReasonCode reasonCode;
  81.             }
  82.             #endregion
  83.  
  84.             internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
  85.             {
  86.                 this.client = client;
  87.                 this.info = info;
  88.             }
  89.  
  90.             /// <summary>
  91.             /// Sets a parameter of the interface whose data type is <see cref="int"/>.
  92.             /// </summary>
  93.             /// <param name="opCode">The opcode of the parameter.</param>
  94.             /// <param name="value">The value to set.</param>
  95.             private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
  96.             {
  97.                 IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
  98.                 Marshal.WriteInt32(valuePtr, value);
  99.                 try
  100.                 {
  101.                     Wlan.ThrowIfError(
  102.                         Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
  103.                 }
  104.                 finally
  105.                 {
  106.                     Marshal.FreeHGlobal(valuePtr);
  107.                 }
  108.             }
  109.  
  110.             /// <summary>
  111.             /// Gets a parameter of the interface whose data type is <see cref="int"/>.
  112.             /// </summary>
  113.             /// <param name="opCode">The opcode of the parameter.</param>
  114.             /// <returns>The integer value.</returns>
  115.             private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
  116.             {
  117.                 IntPtr valuePtr;
  118.                 int valueSize;
  119.                 Wlan.WlanOpcodeValueType opcodeValueType;
  120.                 Wlan.ThrowIfError(
  121.                     Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
  122.                 try
  123.                 {
  124.                     return Marshal.ReadInt32(valuePtr);
  125.                 }
  126.                 finally
  127.                 {
  128.                     Wlan.WlanFreeMemory(valuePtr);
  129.                 }
  130.             }
  131.  
  132.             public bool GetHostedNetworkSupport()
  133.             {
  134.                 return GetInterfaceInt(Wlan.WlanIntfOpcode.HostedNetworkCapable)!=0;
  135.             }
  136.  
  137.             /// <summary>
  138.             /// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured.
  139.             /// </summary>
  140.             /// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value>
  141.             public bool Autoconf
  142.             {
  143.                 get
  144.                 {
  145.                     return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0;
  146.                 }
  147.                 set
  148.                 {
  149.                     SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0);
  150.                 }
  151.             }
  152.  
  153.             /// <summary>
  154.             /// Gets or sets the BSS type for the indicated interface.
  155.             /// </summary>
  156.             /// <value>The type of the BSS.</value>
  157.             public Wlan.Dot11BssType BssType
  158.             {
  159.                 get
  160.                 {
  161.                     return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType);
  162.                 }
  163.                 set
  164.                 {
  165.                     SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value);
  166.                 }
  167.             }
  168.  
  169.             /// <summary>
  170.             /// Gets the state of the interface.
  171.             /// </summary>
  172.             /// <value>The state of the interface.</value>
  173.             public Wlan.WlanInterfaceState InterfaceState
  174.             {
  175.                 get
  176.                 {
  177.                     return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState);
  178.                 }
  179.             }
  180.  
  181.             /// <summary>
  182.             /// Gets the channel.
  183.             /// </summary>
  184.             /// <value>The channel.</value>
  185.             /// <remarks>Not supported on Windows XP SP2.</remarks>
  186.             public int Channel
  187.             {
  188.                 get
  189.                 {
  190.                     return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber);
  191.                 }                
  192.             }
  193.  
  194.             /// <summary>
  195.             /// Gets the RSSI.
  196.             /// </summary>
  197.             /// <value>The RSSI.</value>
  198.             /// <remarks>Not supported on Windows XP SP2.</remarks>
  199.             public int RSSI
  200.             {
  201.                 get
  202.                 {
  203.                     return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI);
  204.                 }
  205.             }
  206.  
  207.             /// <summary>
  208.             /// Gets the current operation mode.
  209.             /// </summary>
  210.             /// <value>The current operation mode.</value>
  211.             /// <remarks>Not supported on Windows XP SP2.</remarks>
  212.             public Wlan.Dot11OperationMode CurrentOperationMode
  213.             {
  214.                 get
  215.                 {
  216.                     return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode);
  217.                 }
  218.             }
  219.  
  220.             /// <summary>
  221.             /// Gets the attributes of the current connection.
  222.             /// </summary>
  223.             /// <value>The current connection attributes.</value>
  224.             /// <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>
  225.             public Wlan.WlanConnectionAttributes CurrentConnection
  226.             {
  227.                 get
  228.                 {
  229.                     int valueSize;
  230.                     IntPtr valuePtr;
  231.                     Wlan.WlanOpcodeValueType opcodeValueType;
  232.                     Wlan.ThrowIfError(
  233.                         Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
  234.                     try
  235.                     {
  236.                             return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
  237.                     }
  238.                     finally
  239.                     {
  240.                         Wlan.WlanFreeMemory(valuePtr);
  241.                     }
  242.                 }
  243.             }
  244.  
  245.             /// <summary>
  246.             /// Requests a scan for available networks.
  247.             /// </summary>
  248.             /// <remarks>
  249.             /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  250.             /// </remarks>
  251.             public void Scan()
  252.             {
  253.                 Wlan.ThrowIfError(
  254.                     Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
  255.             }
  256.  
  257.             /// <summary>
  258.             /// Converts a pointer to a available networks list (header + entries) to an array of available network entries.
  259.             /// </summary>
  260.             /// <param name="bssListPtr">A pointer to an available networks list's header.</param>
  261.             /// <returns>An array of available network entries.</returns>
  262.             private Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr)
  263.             {
  264.                 Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader));
  265.                 long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader));
  266.                 Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems];
  267.                 for (int i = 0; i < availNetListHeader.numberOfItems; ++i)
  268.                 {
  269.                     availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork));
  270.                     availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork));
  271.                 }
  272.                 return availNets;
  273.             }
  274.  
  275.             /// <summary>
  276.             /// Retrieves the list of available networks.
  277.             /// </summary>
  278.             /// <param name="flags">Controls the type of networks returned.</param>
  279.             /// <returns>A list of the available networks.</returns>
  280.             public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
  281.             {
  282.                 IntPtr availNetListPtr;
  283.                 Wlan.ThrowIfError(
  284.                     Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
  285.                 try
  286.                 {
  287.                     return ConvertAvailableNetworkListPtr(availNetListPtr);
  288.                 }
  289.                 finally
  290.                 {
  291.                     Wlan.WlanFreeMemory(availNetListPtr);
  292.                 }
  293.             }
  294.  
  295.             /// <summary>
  296.             /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries.
  297.             /// </summary>
  298.             /// <param name="bssListPtr">A pointer to a BSS list's header.</param>
  299.             /// <returns>An array of BSS entries.</returns>
  300.             private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr)
  301.             {
  302.                 Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader));
  303.                 long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader));
  304.                 Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems];
  305.                 for (int i=0; i<bssListHeader.numberOfItems; ++i)
  306.                 {
  307.                     bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry));
  308.                     bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry));
  309.                 }
  310.                 return bssEntries;
  311.             }
  312.  
  313.             /// <summary>
  314.             /// Retrieves the basic service sets (BSS) list of all available networks.
  315.             /// </summary>
  316.             public Wlan.WlanBssEntry[] GetNetworkBssList()
  317.             {
  318.                 IntPtr bssListPtr;
  319.                 Wlan.ThrowIfError(
  320.                     Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
  321.                 try
  322.                 {
  323.                     return ConvertBssListPtr(bssListPtr);
  324.                 }
  325.                 finally
  326.                 {
  327.                     Wlan.WlanFreeMemory(bssListPtr);
  328.                 }
  329.             }
  330.  
  331.             /// <summary>
  332.             /// Retrieves the basic service sets (BSS) list of the specified network.
  333.             /// </summary>
  334.             /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
  335.             /// <param name="bssType">Indicates the BSS type of the network.</param>
  336.             /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
  337.             public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
  338.             {
  339.                 IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
  340.                 Marshal.StructureToPtr(ssid, ssidPtr, false);
  341.                 try
  342.                 {
  343.                     IntPtr bssListPtr;
  344.                     Wlan.ThrowIfError(
  345.                         Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
  346.                     try
  347.                     {
  348.                         return ConvertBssListPtr(bssListPtr);
  349.                     }
  350.                     finally
  351.                     {
  352.                         Wlan.WlanFreeMemory(bssListPtr);
  353.                     }
  354.                 }
  355.                 finally
  356.                 {
  357.                     Marshal.FreeHGlobal(ssidPtr);
  358.                 }
  359.             }
  360.  
  361.             /// <summary>
  362.             /// Connects to a network defined by a connection parameters structure.
  363.             /// </summary>
  364.             /// <param name="connectionParams">The connection paramters.</param>
  365.             protected void Connect(Wlan.WlanConnectionParameters connectionParams)
  366.             {
  367.                 Wlan.ThrowIfError(
  368.                     Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
  369.             }
  370.  
  371.             /// <summary>
  372.             /// Requests a connection (association) to the specified wireless network.
  373.             /// </summary>
  374.             /// <remarks>
  375.             /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  376.             /// </remarks>
  377.             public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
  378.             {
  379.                 Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
  380.                 connectionParams.wlanConnectionMode = connectionMode;
  381.                 connectionParams.profile = profile;
  382.                 connectionParams.dot11BssType = bssType;
  383.                 connectionParams.flags = 0;
  384.                 Connect(connectionParams);
  385.             }
  386.             
  387.             /// <summary>
  388.             /// Connects (associates) to the specified wireless network, returning either on a success to connect
  389.             /// or a failure.
  390.             /// </summary>
  391.             /// <param name="connectionMode"></param>
  392.             /// <param name="bssType"></param>
  393.             /// <param name="profile"></param>
  394.             /// <param name="connectTimeout"></param>
  395.             /// <returns></returns>
  396.             public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
  397.             {
  398.                 queueEvents = true;
  399.                 try
  400.                 {
  401.                     Connect(connectionMode, bssType, profile);
  402.                     while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
  403.                     {
  404.                         lock (eventQueue)
  405.                         {
  406.                             while (eventQueue.Count != 0)
  407.                             {
  408.                                 object e = eventQueue.Dequeue();
  409.                                 if (e is WlanConnectionNotificationEventData)
  410.                                 {
  411.                                     WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
  412.                                     // Check if the conditions are good to indicate either success or failure.
  413.                                     if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
  414.                                     {
  415.                                         switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
  416.                                         {
  417.                                             case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
  418.                                                 if (wlanConnectionData.connNotifyData.profileName == profile)
  419.                                                     return true;
  420.                                                 break;
  421.                                         }
  422.                                     }
  423.                                     break;
  424.                                 }
  425.                             }
  426.                         }
  427.                     }
  428.                 }
  429.                 finally
  430.                 {
  431.                     queueEvents = false;
  432.                     eventQueue.Clear();
  433.                 }
  434.                 return false; // timeout expired and no "connection complete"
  435.             }
  436.  
  437.             /// <summary>
  438.             /// Connects to the specified wireless network.
  439.             /// </summary>
  440.             /// <remarks>
  441.             /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
  442.             /// </remarks>
  443.             public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
  444.             {
  445.                 Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
  446.                 connectionParams.wlanConnectionMode = connectionMode;
  447.                 connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
  448.                 Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
  449.                 connectionParams.dot11BssType = bssType;
  450.                 connectionParams.flags = flags;
  451.                 Connect(connectionParams);
  452.                 Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
  453.                 Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
  454.             }
  455.  
  456.             /// <summary>
  457.             /// Deletes a profile.
  458.             /// </summary>
  459.             /// <param name="profileName">
  460.             /// The name of the profile to be deleted. Profile names are case-sensitive.
  461.             /// 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>.
  462.             /// </param>
  463.             public void DeleteProfile(string profileName)
  464.             {
  465.                 Wlan.ThrowIfError(
  466.                     Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
  467.             }
  468.  
  469.             /// <summary>
  470.             /// Disconnects an interface from its current network.
  471.             /// </summary>
  472.             public void Disconnect()
  473.             {
  474.                 Wlan.ThrowIfError(
  475.                     Wlan.WlanDisconnect(client.clientHandle, info.interfaceGuid, IntPtr.Zero));
  476.             }
  477.  
  478.             /// <summary>
  479.             /// Sets the profile.
  480.             /// </summary>
  481.             /// <param name="flags">The flags to set on the profile.</param>
  482.             /// <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>
  483.             /// <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>
  484.             /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
  485.             public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
  486.             {
  487.                 Wlan.WlanReasonCode reasonCode;
  488.                 //Wlan.ThrowIfError(
  489.                         Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode);//);
  490.                 return reasonCode;
  491.             }
  492.  
  493.             /// <summary>
  494.             /// Gets the profile's XML specification.
  495.             /// </summary>
  496.             /// <param name="profileName">The name of the profile.</param>
  497.             /// <returns>The XML document.</returns>
  498.             public string GetProfileXml(string profileName)
  499.             {
  500.                 IntPtr profileXmlPtr;
  501.                 Wlan.WlanProfileFlags flags = Wlan.WlanProfileFlags.PlainTextKey;
  502.                 Wlan.WlanAccess access;
  503.                 Wlan.ThrowIfError(
  504.                     Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, ref flags,
  505.                                    out access));
  506.                 try
  507.                 {
  508.                     return Marshal.PtrToStringUni(profileXmlPtr);
  509.                 }
  510.                 finally
  511.                 {
  512.                     Wlan.WlanFreeMemory(profileXmlPtr);
  513.                 }
  514.             }
  515.  
  516.             /// <summary>
  517.             /// Gets the information of all profiles on this interface.
  518.             /// </summary>
  519.             /// <returns>The profiles information.</returns>
  520.             public Wlan.WlanProfileInfo[] GetProfiles()
  521.             {
  522.                 IntPtr profileListPtr;
  523.                 Wlan.ThrowIfError(
  524.                     Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
  525.                 try
  526.                 {
  527.                     Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
  528.                     Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
  529.                     long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
  530.                     for (int i=0; i<header.numberOfItems; ++i)
  531.                     {
  532.                         Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo));
  533.                         profileInfos[i] = profileInfo;
  534.                         profileListIterator += Marshal.SizeOf(profileInfo);
  535.                     }
  536.                     return profileInfos;
  537.                 }
  538.                 finally
  539.                 {
  540.                     Wlan.WlanFreeMemory(profileListPtr);
  541.                 }
  542.             }
  543.  
  544.             internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)
  545.             {
  546.                 if (WlanConnectionNotification != null)
  547.                     WlanConnectionNotification(notifyData, connNotifyData);
  548.  
  549.                 if (queueEvents)
  550.                 {
  551.                     WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData();
  552.                     queuedEvent.notifyData = notifyData;
  553.                     queuedEvent.connNotifyData = connNotifyData;
  554.                     EnqueueEvent(queuedEvent);
  555.                 }
  556.             }
  557.  
  558.             internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode)
  559.             {
  560.                 if (WlanReasonNotification != null)
  561.                     WlanReasonNotification(notifyData, reasonCode);
  562.                 if (queueEvents)
  563.                 {
  564.                     WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData();
  565.                     queuedEvent.notifyData = notifyData;
  566.                     queuedEvent.reasonCode = reasonCode;
  567.                     EnqueueEvent(queuedEvent);
  568.                 }
  569.             }
  570.  
  571.             internal void OnWlanNotification(Wlan.WlanNotificationData notifyData)
  572.             {
  573.                 if (WlanNotification != null)
  574.                     WlanNotification(notifyData);
  575.             }
  576.  
  577.             /// <summary>
  578.             /// Enqueues a notification event to be processed serially.
  579.             /// </summary>
  580.             private void EnqueueEvent(object queuedEvent)
  581.             {
  582.                 lock (eventQueue)
  583.                     eventQueue.Enqueue(queuedEvent);
  584.                 eventQueueFilled.Set();
  585.             }
  586.  
  587.             /// <summary>
  588.             /// Gets the network interface of this wireless interface.
  589.             /// </summary>
  590.             /// <remarks>
  591.             /// The network interface allows querying of generic network properties such as the interface's IP address.
  592.             /// </remarks>
  593.             public NetworkInterface NetworkInterface
  594.             {
  595.                 get
  596.                 {
  597.                     // Do not cache the NetworkInterface; We need it fresh
  598.                     // each time cause otherwise it caches the IP information.
  599.                     foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces())
  600.                     {
  601.                         Guid netIfaceGuid = new Guid(netIface.Id);
  602.                         if (netIfaceGuid.Equals(info.interfaceGuid))
  603.                         {
  604.                             return netIface;
  605.                         }
  606.                     }
  607.                     return null;
  608.                 }
  609.             }
  610.  
  611.             /// <summary>
  612.             /// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value).
  613.             /// </summary>
  614.             public Guid InterfaceGuid
  615.             {
  616.                 get { return info.interfaceGuid; }
  617.             }
  618.  
  619.             /// <summary>
  620.             /// The description of the interface.
  621.             /// This is a user-immutable string containing the vendor and model name of the adapter.
  622.             /// </summary>
  623.             public string InterfaceDescription
  624.             {
  625.                 get { return info.interfaceDescription; }
  626.             }
  627.  
  628.             /// <summary>
  629.             /// The friendly name given to the interface by the user (e.g. "Local Area Network Connection").
  630.             /// </summary>
  631.             public string InterfaceName
  632.             {
  633.                 get { return NetworkInterface.Name; }
  634.             }
  635.         }
  636.  
  637.         private IntPtr clientHandle;
  638.         private uint negotiatedVersion;
  639.         private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback;
  640.  
  641.         private Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>();
  642.  
  643.         /// <summary>
  644.         /// Creates a new instance of a Native Wifi service client.
  645.         /// </summary>
  646.         public WlanClient()
  647.         {
  648.             Wlan.ThrowIfError(
  649.                 Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
  650.             try
  651.             {
  652.                 Wlan.WlanNotificationSource prevSrc;
  653.                 wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification);
  654.                 Wlan.ThrowIfError(
  655.                     Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
  656.             }
  657.             catch
  658.             {
  659.                 Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
  660.                 throw;
  661.             }
  662.         }
  663.  
  664.         ~WlanClient()
  665.         {
  666.             Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
  667.         }
  668.  
  669.         private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
  670.         {
  671.             int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
  672.             if (notifyData.dataSize < expectedSize)
  673.                 return null;
  674.  
  675.             Wlan.WlanConnectionNotificationData connNotifyData =
  676.                 (Wlan.WlanConnectionNotificationData)
  677.                 Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
  678.             if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
  679.             {
  680.                 IntPtr profileXmlPtr = new IntPtr(
  681.                     notifyData.dataPtr.ToInt64() +
  682.                     Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
  683.                 connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
  684.             }
  685.             return connNotifyData;
  686.         }
  687.  
  688.         private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
  689.         {
  690.             WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null;
  691.  
  692.             switch(notifyData.notificationSource)
  693.             {
  694.                 case Wlan.WlanNotificationSource.ACM:
  695.                     switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
  696.                     {
  697.                         case Wlan.WlanNotificationCodeAcm.ConnectionStart:
  698.                         case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
  699.                         case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
  700.                         case Wlan.WlanNotificationCodeAcm.Disconnecting:
  701.                         case Wlan.WlanNotificationCodeAcm.Disconnected:
  702.                             Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
  703.                             if (connNotifyData.HasValue)
  704.                                 if (wlanIface != null)
  705.                                     wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
  706.                             break;
  707.                         case Wlan.WlanNotificationCodeAcm.ScanComplete:
  708.                         case Wlan.WlanNotificationCodeAcm.ScanFail:
  709.                             {
  710.                                 if (notifyData.dataSize >= Marshal.SizeOf(new Int32()))
  711.                                 {
  712.                                     Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
  713.                                     if (wlanIface != null)
  714.                                         wlanIface.OnWlanReason(notifyData, reasonCode);
  715.                                 }
  716.                             }
  717.                             break;
  718.                     }
  719.                     break;
  720.                 case Wlan.WlanNotificationSource.MSM:
  721.                     switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
  722.                     {
  723.                         case Wlan.WlanNotificationCodeMsm.Associating:
  724.                         case Wlan.WlanNotificationCodeMsm.Associated:
  725.                         case Wlan.WlanNotificationCodeMsm.Authenticating:
  726.                         case Wlan.WlanNotificationCodeMsm.Connected:
  727.                         case Wlan.WlanNotificationCodeMsm.RoamingStart:
  728.                         case Wlan.WlanNotificationCodeMsm.RoamingEnd:
  729.                         case Wlan.WlanNotificationCodeMsm.Disassociating:
  730.                         case Wlan.WlanNotificationCodeMsm.Disconnected:
  731.                         case Wlan.WlanNotificationCodeMsm.PeerJoin:
  732.                         case Wlan.WlanNotificationCodeMsm.PeerLeave:
  733.                         case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
  734.                             Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
  735.                             if (connNotifyData.HasValue)
  736.                                 if (wlanIface != null)
  737.                                     wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
  738.                             break;
  739.                     }
  740.                     break;
  741.             }
  742.             
  743.             if (wlanIface != null)
  744.                 wlanIface.OnWlanNotification(notifyData);
  745.         }
  746.  
  747.         /// <summary>
  748.         /// Gets the WLAN interfaces.
  749.         /// </summary>
  750.         /// <value>The WLAN interfaces.</value>
  751.         public WlanInterface[] Interfaces
  752.         {
  753.             get
  754.             {
  755.                 IntPtr ifaceList;
  756.                 Wlan.ThrowIfError(
  757.                     Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList));
  758.                 try
  759.                 {
  760.                     Wlan.WlanInterfaceInfoListHeader header =
  761.                         (Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader));
  762.                     Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header);
  763.                     WlanInterface[] interfaces = new WlanInterface[header.numberOfItems];
  764.                     List<Guid> currentIfaceGuids = new List<Guid>();
  765.                     for (int i = 0; i < header.numberOfItems; ++i)
  766.                     {
  767.                         Wlan.WlanInterfaceInfo info =
  768.                             (Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo));
  769.                         listIterator += Marshal.SizeOf(info);
  770.                         WlanInterface wlanIface;
  771.                         currentIfaceGuids.Add(info.interfaceGuid);
  772.                         if (ifaces.ContainsKey(info.interfaceGuid))
  773.                             wlanIface = ifaces[info.interfaceGuid];
  774.                         else
  775.                             wlanIface = new WlanInterface(this, info);
  776.                         interfaces[i] = wlanIface;
  777.                         ifaces[info.interfaceGuid] = wlanIface;
  778.                     }
  779.  
  780.                     // Remove stale interfaces
  781.                     Queue<Guid> deadIfacesGuids = new Queue<Guid>();
  782.                     foreach (Guid ifaceGuid in ifaces.Keys)
  783.                     {
  784.                         if (!currentIfaceGuids.Contains(ifaceGuid))
  785.                             deadIfacesGuids.Enqueue(ifaceGuid);
  786.                     }
  787.                     while(deadIfacesGuids.Count != 0)
  788.                     {
  789.                         Guid deadIfaceGuid = deadIfacesGuids.Dequeue();
  790.                         ifaces.Remove(deadIfaceGuid);
  791.                     }
  792.  
  793.                     return interfaces;
  794.                 }
  795.                 finally
  796.                 {
  797.                     Wlan.WlanFreeMemory(ifaceList);
  798.                 }
  799.             }
  800.         }
  801.  
  802.         /// <summary>
  803.         /// Gets a string that describes a specified reason code.
  804.         /// </summary>
  805.         /// <param name="reasonCode">The reason code.</param>
  806.         /// <returns>The string.</returns>
  807.         public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
  808.         {
  809.             StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
  810.             Wlan.ThrowIfError(
  811.                 Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
  812.             return sb.ToString();
  813.         }
  814.         /// <summary>
  815.         /// Gets a string that describes a specified reason code.
  816.         /// </summary>
  817.         /// <param name="reasonCode">The hosted network reason code.</param>
  818.         /// <returns>The string.</returns>
  819.         public string GetStringForHostedNetworkReasonCode(Wlan.WlanHostedNetworkReason reasonCode)
  820.         {
  821.             // the windows wlanapi seems like it should really have this itself, so that the results are
  822.             // internationalized, etc.  but it seems to be missing, so I'm implementing by hand here.
  823.  
  824.             string results = "Unknown";
  825.             switch (reasonCode)
  826.             {
  827.  
  828.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_success:
  829.                     results = "Success";
  830.                     break;
  831.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_unspecified:
  832.                     results = "Unknown error";
  833.                     break;
  834.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_bad_parameters:
  835.                     results = "Bad parameters";
  836.                     break;
  837.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_shutting_down:
  838.                     results = "Service is shutting down";
  839.                     break;
  840.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_insufficient_resources:
  841.                     results = "Service is out of resources";
  842.                     break;
  843.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_elevation_required:
  844.                     results = "This operation requires elevation";
  845.                     break;
  846.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_read_only:
  847.                     results = "An attempt was made to write read-only data";
  848.                     break;
  849.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_persistence_failed:
  850.                     results = "Data persistence failed";
  851.                     break;
  852.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_crypt_error:
  853.                     results = "A cryptographic error occurred";
  854.                     break;
  855.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_impersonation:
  856.                     results = "User impersonation failed";
  857.                     break;
  858.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_stop_before_start:
  859.                     results = "An incorrect function call sequence was made";
  860.                     break;
  861.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_interface_available:
  862.                     results = "A wireless interface has become available";
  863.                     break;
  864.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_interface_unavailable:
  865.                     results = "A wireless interface has become unavailable";
  866.                     break;
  867.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_miniport_stopped:
  868.                     results = "The wireless miniport driver stopped the Hosted Network";
  869.                     break;
  870.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_miniport_started:
  871.                     results = "The wireless miniport driver status changed";
  872.                     break;
  873.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_incompatible_connection_started:
  874.                     results = "An incompatible connection started";
  875.                     break;
  876.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_incompatible_connection_stopped:
  877.                     results = "An incompatible connection stopped";
  878.                     break;
  879.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_user_action:
  880.                     results = "A state change occurred that was caused by explicit user action";
  881.                     break;
  882.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_client_abort:
  883.                     results = "A state change occurred that was caused by client abort";
  884.                     break;
  885.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_ap_start_failed:
  886.                     results = "The driver for the wireless Hosted Network failed to start";
  887.                     break;
  888.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_arrived:
  889.                     results = "A peer connected to the wireless Hosted Network";
  890.                     break;
  891.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_departed:
  892.                     results = "A peer disconnected from the wireless Hosted Network";
  893.                     break;
  894.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_peer_timeout:
  895.                     results = "A peer timed out";
  896.                     break;
  897.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_gp_denied:
  898.                     results = "The operation was denied by group policy";
  899.                     break;
  900.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_unavailable:
  901.                     results = "The Wireless LAN service is not running";
  902.                     break;
  903.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_device_change:
  904.                     results = "The wireless adapter used by the wireless Hosted Network changed";
  905.                     break;
  906.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_properties_change:
  907.                     results = "The properties of the wireless Hosted Network changed";
  908.                     break;
  909.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_virtual_station_blocking_use:
  910.                     results = "A virtual station is active and blocking operation";
  911.                     break;
  912.                 case Wlan.WlanHostedNetworkReason.wlan_hosted_network_reason_service_available_on_virtual_station:
  913.                     results = "An identical service is available on a virtual station";
  914.                     break;
  915.  
  916.             }
  917.             return results;
  918.  
  919.         }
  920.  
  921.         // Hosted Network methods
  922.         /// <summary>
  923.         /// Connects to a network defined by a connection parameters structure.
  924.         /// </summary>
  925.         /// <param name="connectionParams">The connection paramters.</param>
  926.         public void WlanHostedNetworkStartUsing(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  927.         {
  928.  
  929.           
  930.             Wlan.ThrowIfError(
  931.                 Wlan.WlanHostedNetworkStartUsing(clientHandle,out reasoncode, IntPtr.Zero));
  932.         }
  933.         /** Makes this app stop using the network.  If the network was started with WlanHostedNetworkStartUsing,
  934.          * then this might cause it to exit, if we were the last app using it.  If it was force started,
  935.          * then it will keep running whether we're here or not.
  936.          */ 
  937.         public void  WlanHostedNetworkStopUsing(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  938.         {
  939.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkStopUsing(clientHandle, out reasoncode,IntPtr.Zero));
  940.         }
  941.         /** Force the network to stop running right now, even if others are using it. */
  942.         public void WlanHostedNetworkForceStop(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  943.         {
  944.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkForceStop(clientHandle,  out reasoncode, IntPtr.Zero));
  945.         }
  946.         /** Makes the network start so that it will continue running even after the app exits, DOES require
  947.          * you to be an Administrator */
  948.         public void WlanHostedNetworkForceStart(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  949.         {
  950.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkForceStart(clientHandle, out reasoncode, IntPtr.Zero));
  951.         }
  952.  
  953.         public void WlanHostedNetworkInitSettings(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  954.         {
  955.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkInitSettings(clientHandle, out reasoncode, IntPtr.Zero));
  956.         }
  957.         /** Calls WlanHostedNetworkSetProperty and sets the connection settings which are SSID and max number of peers
  958.          * allowed to call at any one time. 
  959.          * TODO:  need a method to handle the enable opcode.  (which will only work with elevated permissions).
  960.          */
  961.         public void WlanHostedNetworkSetConnectionProperties(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode,
  962.             String ssidName,   int maxPeers        )
  963.         {
  964.             Wlan.Dot11Ssid hostedNetworkSSIDdot11Ssid= GetSSIDForString(ssidName);
  965.             Wlan.WlanHostedNetworkConnectionSettings settings = new Wlan.WlanHostedNetworkConnectionSettings();
  966.             settings.dwMaxNumberOfPeers = maxPeers;
  967.             settings.hostedNetworkSSIDdot11Ssid = hostedNetworkSSIDdot11Ssid;
  968.             IntPtr ptr;
  969.             ptr = Marshal.AllocHGlobal(Marshal.SizeOf(settings));
  970.             Marshal.StructureToPtr(settings, ptr, false);
  971.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkSetProperty(clientHandle, 
  972.                 Wlan.WlanHostedNetworkOpcode.wlan_hosted_network_opcode_connection_settings,
  973.                 Marshal.SizeOf(settings),
  974.                 ptr,            
  975.                 out reasoncode, IntPtr.Zero));
  976.         }
  977.         public void WlanHostedNetworkSetEnabled(out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode,
  978.             bool enable)
  979.         {
  980.             IntPtr ptr;
  981.             ptr = Marshal.AllocHGlobal(Marshal.SizeOf(enable));
  982.             Marshal.StructureToPtr(enable, ptr, false);
  983.             Wlan.ThrowIfError(Wlan.WlanHostedNetworkSetProperty(clientHandle,
  984.                 Wlan.WlanHostedNetworkOpcode.wlan_hosted_network_opcode_enable,
  985.                 Marshal.SizeOf(enable),
  986.                 ptr,
  987.                 out reasoncode, IntPtr.Zero));
  988.         }
  989.  
  990.         public List<Wlan.WlanHostedNetworkPeerState> WlanHostedNetworkQueryStatus(out NativeWifi.Wlan.WlanHostedNetworkStatusHeader networkstatus)
  991.         {
  992.             IntPtr statusptr = IntPtr.Zero;
  993.             networkstatus = new Wlan.WlanHostedNetworkStatusHeader();
  994.  
  995.             List<Wlan.WlanHostedNetworkPeerState> currentPeers = new List<Wlan.WlanHostedNetworkPeerState>();
  996.  
  997.             int i = 0;
  998.             int retval;
  999.             while ((retval = Wlan.WlanHostedNetworkQueryStatus(clientHandle, out statusptr, IntPtr.Zero)) != 0 &&
  1000.                     i < 10)
  1001.             {
  1002.                 System.Threading.Thread.Sleep(50);
  1003.                 i++;
  1004.             }
  1005.           
  1006.             Wlan.ThrowIfError(retval);
  1007.             try
  1008.                 {
  1009.                     Wlan.WlanHostedNetworkStatusHeader hostedStatus =
  1010.                         (Wlan.WlanHostedNetworkStatusHeader) Marshal.PtrToStructure(statusptr, typeof (Wlan.WlanHostedNetworkStatusHeader));
  1011.  
  1012.                     networkstatus = hostedStatus;
  1013.                    /* networkstatus.HostedNetworkState = hostedStatus.HostedNetworkState;
  1014.                     networkstatus.IPDeviceID = hostedStatus.IPDeviceID;
  1015.                     networkstatus.wlanHostedNetworkBSSID = hostedStatus.wlanHostedNetworkBSSID;
  1016.                     networkstatus.dot11PhyType = hostedStatus.dot11PhyType;
  1017.                     networkstatus.ChannelFrequency = hostedStatus.ChannelFrequency;
  1018.                     networkstatus.NumberOfPeers = hostedStatus.NumberOfPeers;
  1019.                    */
  1020.                     // so NumberOfPeers has the number of peers that are in the array.  
  1021.                     if ((hostedStatus.HostedNetworkState == Wlan.WlanHostedNetworkState.wlan_hosted_network_active) &&
  1022.                         (hostedStatus.NumberOfPeers > 0))
  1023.                     {
  1024.                         // iterate through the peers
  1025.                         Int64 listIterator = statusptr.ToInt64() + Marshal.SizeOf(hostedStatus);
  1026.                         
  1027.                         for (int peer = 0; peer < hostedStatus.NumberOfPeers; ++peer)
  1028.                         {
  1029.  
  1030.                             Wlan.WlanHostedNetworkPeerState info =
  1031.                                 (Wlan.WlanHostedNetworkPeerState)Marshal.PtrToStructure(new IntPtr(listIterator), typeof(Wlan.WlanHostedNetworkPeerState));
  1032.                             listIterator += Marshal.SizeOf(info);
  1033.                             //Wlan.WlanHostedNetworkPeerState wlanIface;
  1034.                             currentPeers.Add(info);
  1035.                             // Console.WriteLine("\t\tpeer: {0} {1}", GetStringForMAC(info.PeerMacAddress), info.PeerAuthState);                          
  1036.                         }
  1037.                     }
  1038.             }
  1039.             finally
  1040.             {
  1041.                 Wlan.WlanFreeMemory(statusptr);
  1042.             }
  1043.             return currentPeers;
  1044.         }
  1045.  
  1046.         public void WlanHostedNetworkSetSecondaryKey(string passphrase,bool persistent, bool isPassPhrase, 
  1047.             out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  1048.         {
  1049.             
  1050.             uint length = (uint) passphrase.Length;
  1051.             if (isPassPhrase)
  1052.             {
  1053.                 // need to add one for the \0 at end of string
  1054.                 length++;
  1055.             }
  1056.             // Wlan.ThrowIfError(
  1057.                  Wlan.WlanHostedNetworkSetSecondaryKey(clientHandle, length, passphrase, 
  1058.                 isPassPhrase, persistent, out reasoncode, IntPtr.Zero);
  1059.             //);
  1060.  
  1061.         }
  1062.  
  1063.         /*
  1064.          * Get the current security key
  1065.          */
  1066.         public void WlanHostedNetworkQuerySecondaryKey(out String passphrase, out bool isPassPhrase, out bool isPersistent, out NativeWifi.Wlan.WlanHostedNetworkReason reasoncode)
  1067.         {
  1068.            
  1069.             String buffer = "";
  1070.             uint length = 0;
  1071.              Wlan.ThrowIfError(Wlan.WlanHostedNetworkQuerySecondaryKey(clientHandle, out length, out buffer, 
  1072.                 out isPassPhrase, out isPersistent,  out reasoncode, IntPtr.Zero));          
  1073.             
  1074.             passphrase = buffer;
  1075.  
  1076.             
  1077.         }
  1078.  
  1079.         /// <summary>
  1080.         /// Converts a 802.11 SSID to a string.
  1081.         /// </summary>
  1082.         public static string GetStringForSSID(Wlan.Dot11Ssid ssid)
  1083.         {
  1084.             return Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
  1085.         }
  1086.  
  1087.         static Wlan.Dot11Ssid GetSSIDForString(String name)
  1088.         {
  1089.             if (name.Length > 32)
  1090.             {
  1091.                 name = name.Substring(0, 32);
  1092.             }
  1093.             Wlan.Dot11Ssid ssid = new Wlan.Dot11Ssid();
  1094.             ssid.SSID = new byte[32];
  1095.             System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  1096.             Byte[] bytes = encoding.GetBytes(name);
  1097.             uint length = (uint) bytes.Length;
  1098.             
  1099.             ssid.SSIDLength = length;
  1100.             for (int i = 0; i < ssid.SSID.Length; i++)
  1101.             {
  1102.                 if (i < length)
  1103.                 {
  1104.                     ssid.SSID[i] = bytes[i];
  1105.                 }
  1106.                 else
  1107.                 {
  1108.                     ssid.SSID[i] = 0;
  1109.  
  1110.                 }
  1111.             }
  1112.             return ssid;
  1113.         }
  1114.         /// <summary>
  1115.         /// Converts a 802.11 MAC to a string.
  1116.         /// </summary>
  1117.         public static string GetStringForMAC(Wlan.Dot11MacAddress mac)
  1118.         {
  1119.  
  1120.             return ConvertToHexString(mac.mac1) + ":" +
  1121.                 ConvertToHexString(mac.mac2) + ":" +
  1122.                 ConvertToHexString(mac.mac3) + ":" +
  1123.                 ConvertToHexString(mac.mac4) + ":" +
  1124.                 ConvertToHexString(mac.mac5) + ":" +
  1125.                 ConvertToHexString(mac.mac6);
  1126.  
  1127.         }
  1128.         public static string ConvertToHexString(uint value)
  1129.         {
  1130.             StringBuilder builder = new StringBuilder("");
  1131.             builder.Append(Convert.ToString(value, 16).PadLeft(2, '0'));
  1132.             return builder.ToString();
  1133.         }
  1134.         public static string ConvertPerAuthStateToString(NativeWifi.Wlan.WlanHostedNetworkPeerAuthState val)
  1135.         {
  1136.             if (val == NativeWifi.Wlan.WlanHostedNetworkPeerAuthState.wlan_hosted_network_peer_state_invalid)
  1137.             {
  1138.                 return "Invalid";
  1139.             }
  1140.             else if (val == NativeWifi.Wlan.WlanHostedNetworkPeerAuthState.wlan_hosted_network_peer_state_authenticated)
  1141.             {
  1142.                 return "OK";
  1143.             }
  1144.             else
  1145.             {
  1146.                 return "ERROR";
  1147.             }
  1148.         }
  1149.     }
  1150.  
  1151. }
  1152.