using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text;
namespace Windows.Common.Wifi
{
///
/// Represents a client to the Zeroconf (Native Wifi) service.
///
///
/// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance
/// of this class.
///
public class WlanClient
{
///
/// Represents a Wifi network interface.
///
public class WlanInterface
{
private WlanClient client;
private Wlan.WlanInterfaceInfo info;
#region Events
///
/// Represents a method that will handle events.
///
/// The notification data.
public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData);
///
/// Represents a method that will handle events.
///
/// The notification data.
/// The notification data.
public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData);
///
/// Represents a method that will handle events.
///
/// The notification data.
/// The reason code.
public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode);
///
/// Occurs when an event of any kind occurs on a WLAN interface.
///
public event WlanNotificationEventHandler WlanNotification;
///
/// Occurs when a WLAN interface changes connection state.
///
public event WlanConnectionNotificationEventHandler WlanConnectionNotification;
///
/// Occurs when a WLAN operation fails due to some reason.
///
public event WlanReasonNotificationEventHandler WlanReasonNotification;
#endregion
#region Event queue
private bool queueEvents;
private AutoResetEvent eventQueueFilled = new AutoResetEvent(false);
private Queue eventQueue = new Queue();
private struct WlanConnectionNotificationEventData
{
public Wlan.WlanNotificationData notifyData;
public Wlan.WlanConnectionNotificationData connNotifyData;
}
private struct WlanReasonNotificationData
{
public Wlan.WlanNotificationData notifyData;
public Wlan.WlanReasonCode reasonCode;
}
#endregion
internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info)
{
this.client = client;
this.info = info;
}
///
/// Sets a parameter of the interface whose data type is .
///
/// The opcode of the parameter.
/// The value to set.
private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value)
{
IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(valuePtr, value);
try
{
Wlan.ThrowIfError(
Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
}
finally
{
Marshal.FreeHGlobal(valuePtr);
}
}
///
/// Gets a parameter of the interface whose data type is .
///
/// The opcode of the parameter.
/// The integer value.
private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode)
{
IntPtr valuePtr;
int valueSize;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try
{
return Marshal.ReadInt32(valuePtr);
}
finally
{
Wlan.WlanFreeMemory(valuePtr);
}
}
///
/// Gets or sets a value indicating whether this is automatically configured.
///
/// true if "autoconf" is enabled; otherwise, false .
public bool Autoconf
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0;
}
set
{
SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0);
}
}
///
/// Gets or sets the BSS type for the indicated interface.
///
/// The type of the BSS.
public Wlan.Dot11BssType BssType
{
get
{
return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType);
}
set
{
SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value);
}
}
///
/// Gets the state of the interface.
///
/// The state of the interface.
public Wlan.WlanInterfaceState InterfaceState
{
get
{
return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState);
}
}
///
/// Gets the channel.
///
/// The channel.
/// Not supported on Windows XP SP2.
public int Channel
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber);
}
}
///
/// Gets the RSSI.
///
/// The RSSI.
/// Not supported on Windows XP SP2.
public int RSSI
{
get
{
return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI);
}
}
///
/// Gets the current operation mode.
///
/// The current operation mode.
/// Not supported on Windows XP SP2.
public Wlan.Dot11OperationMode CurrentOperationMode
{
get
{
return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode);
}
}
///
/// Gets the attributes of the current connection.
///
/// The current connection attributes.
/// 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.
public Wlan.WlanConnectionAttributes CurrentConnection
{
get
{
int valueSize;
IntPtr valuePtr;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try
{
return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
}
finally
{
Wlan.WlanFreeMemory(valuePtr);
}
}
}
///
/// Requests a scan for available networks.
///
///
/// The method returns immediately. Progress is reported through the event.
///
public void Scan()
{
Wlan.ThrowIfError(
Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
}
///
/// Converts a pointer to a available networks list (header + entries) to an array of available network entries.
///
/// A pointer to an available networks list's header.
/// An array of available network entries.
private Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr)
{
Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader));
long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader));
Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems];
for (int i = 0; i < availNetListHeader.numberOfItems; ++i)
{
availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork));
availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork));
}
return availNets;
}
///
/// Retrieves the list of available networks.
///
/// Controls the type of networks returned.
/// A list of the available networks.
public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags)
{
IntPtr availNetListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));
try
{
return ConvertAvailableNetworkListPtr(availNetListPtr);
}
finally
{
Wlan.WlanFreeMemory(availNetListPtr);
}
}
///
/// Converts a pointer to a BSS list (header + entries) to an array of BSS entries.
///
/// A pointer to a BSS list's header.
/// An array of BSS entries.
private Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr)
{
Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader));
long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader));
Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems];
for (int i=0; i
/// Retrieves the basic service sets (BSS) list of all available networks.
///
public Wlan.WlanBssEntry[] GetNetworkBssList()
{
IntPtr bssListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));
try
{
return ConvertBssListPtr(bssListPtr);
}
finally
{
Wlan.WlanFreeMemory(bssListPtr);
}
}
///
/// Retrieves the basic service sets (BSS) list of the specified network.
///
/// Specifies the SSID of the network from which the BSS list is requested.
/// Indicates the BSS type of the network.
/// Indicates whether security is enabled on the network.
public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled)
{
IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
Marshal.StructureToPtr(ssid, ssidPtr, false);
try
{
IntPtr bssListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));
try
{
return ConvertBssListPtr(bssListPtr);
}
finally
{
Wlan.WlanFreeMemory(bssListPtr);
}
}
finally
{
Marshal.FreeHGlobal(ssidPtr);
}
}
///
/// Connects to a network defined by a connection parameters structure.
///
/// The connection paramters.
protected void Connect(Wlan.WlanConnectionParameters connectionParams)
{
Wlan.ThrowIfError(
Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
}
///
/// Requests a connection (association) to the specified wireless network.
///
///
/// The method returns immediately. Progress is reported through the event.
///
public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile)
{
Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
connectionParams.wlanConnectionMode = connectionMode;
connectionParams.profile = profile;
connectionParams.dot11BssType = bssType;
connectionParams.flags = 0;
Connect(connectionParams);
}
///
/// Connects (associates) to the specified wireless network, returning either on a success to connect
/// or a failure.
///
///
///
///
///
///
public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout)
{
queueEvents = true;
try
{
Connect(connectionMode, bssType, profile);
while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true))
{
lock (eventQueue)
{
while (eventQueue.Count != 0)
{
object e = eventQueue.Dequeue();
if (e is WlanConnectionNotificationEventData)
{
WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e;
// Check if the conditions are good to indicate either success or failure.
if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)
{
switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
if (wlanConnectionData.connNotifyData.profileName == profile)
return true;
break;
}
}
break;
}
}
}
}
}
finally
{
queueEvents = false;
eventQueue.Clear();
}
return false; // timeout expired and no "connection complete"
}
///
/// Connects to the specified wireless network.
///
///
/// The method returns immediately. Progress is reported through the event.
///
public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags)
{
Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters();
connectionParams.wlanConnectionMode = connectionMode;
connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));
Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false);
connectionParams.dot11BssType = bssType;
connectionParams.flags = flags;
Connect(connectionParams);
Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType());
Marshal.FreeHGlobal(connectionParams.dot11SsidPtr);
}
///
/// Deletes a profile.
///
///
/// The name of the profile to be deleted. Profile names are case-sensitive.
/// 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 -adhoc .
///
public void DeleteProfile(string profileName)
{
Wlan.ThrowIfError(
Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
}
///
/// Sets the profile.
///
/// The flags to set on the profile.
/// The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.
/// If a profile by the given name already exists, then specifies whether to overwrite it (if true ) or return an error (if false ).
/// The resulting code indicating a success or the reason why the profile wasn't valid.
public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite)
{
Wlan.WlanReasonCode reasonCode;
Wlan.ThrowIfError(
Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode));
return reasonCode;
}
///
/// Gets the profile's XML specification.
///
/// The name of the profile.
/// The XML document.
public string GetProfileXml(string profileName)
{
IntPtr profileXmlPtr;
Wlan.WlanProfileFlags flags;
Wlan.WlanAccess access;
Wlan.ThrowIfError(
Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags,
out access));
try
{
return Marshal.PtrToStringUni(profileXmlPtr);
}
finally
{
Wlan.WlanFreeMemory(profileXmlPtr);
}
}
///
/// Gets the information of all profiles on this interface.
///
/// The profiles information.
public Wlan.WlanProfileInfo[] GetProfiles()
{
IntPtr profileListPtr;
Wlan.ThrowIfError(
Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));
try
{
Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader));
Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems];
long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);
for (int i=0; i
/// Enqueues a notification event to be processed serially.
///
private void EnqueueEvent(object queuedEvent)
{
lock (eventQueue)
eventQueue.Enqueue(queuedEvent);
eventQueueFilled.Set();
}
///
/// Gets the network interface of this wireless interface.
///
///
/// The network interface allows querying of generic network properties such as the interface's IP address.
///
public NetworkInterface NetworkInterface
{
get
{
// Do not cache the NetworkInterface; We need it fresh
// each time cause otherwise it caches the IP information.
foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces())
{
Guid netIfaceGuid = new Guid(netIface.Id);
if (netIfaceGuid.Equals(info.interfaceGuid))
{
return netIface;
}
}
return null;
}
}
///
/// The GUID of the interface (same content as the value).
///
public Guid InterfaceGuid
{
get { return info.interfaceGuid; }
}
///
/// The description of the interface.
/// This is a user-immutable string containing the vendor and model name of the adapter.
///
public string InterfaceDescription
{
get { return info.interfaceDescription; }
}
///
/// The friendly name given to the interface by the user (e.g. "Local Area Network Connection").
///
public string InterfaceName
{
get { return NetworkInterface.Name; }
}
}
private IntPtr clientHandle;
private uint negotiatedVersion;
private Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback;
private Dictionary ifaces = new Dictionary();
///
/// Creates a new instance of a Native Wifi service client.
///
public WlanClient()
{
Wlan.ThrowIfError(
Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
try
{
Wlan.WlanNotificationSource prevSrc;
wlanNotificationCallback = new Wlan.WlanNotificationCallbackDelegate(OnWlanNotification);
Wlan.ThrowIfError(
Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
}
catch
{
Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
throw;
}
}
~WlanClient()
{
Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero);
}
private Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData)
{
int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData));
if (notifyData.dataSize < expectedSize)
return null;
Wlan.WlanConnectionNotificationData connNotifyData =
(Wlan.WlanConnectionNotificationData)
Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData));
if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success)
{
IntPtr profileXmlPtr = new IntPtr(
notifyData.dataPtr.ToInt64() +
Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64());
connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr);
}
return connNotifyData;
}
private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context)
{
WlanInterface wlanIface = ifaces.ContainsKey(notifyData.interfaceGuid) ? ifaces[notifyData.interfaceGuid] : null;
switch(notifyData.notificationSource)
{
case Wlan.WlanNotificationSource.ACM:
switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeAcm.ConnectionStart:
case Wlan.WlanNotificationCodeAcm.ConnectionComplete:
case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail:
case Wlan.WlanNotificationCodeAcm.Disconnecting:
case Wlan.WlanNotificationCodeAcm.Disconnected:
Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
if (connNotifyData.HasValue)
if (wlanIface != null)
wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
break;
case Wlan.WlanNotificationCodeAcm.ScanFail:
{
int expectedSize = Marshal.SizeOf(typeof (Wlan.WlanReasonCode));
if (notifyData.dataSize >= expectedSize)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode) Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
}
break;
}
break;
case Wlan.WlanNotificationSource.MSM:
switch((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode)
{
case Wlan.WlanNotificationCodeMsm.Associating:
case Wlan.WlanNotificationCodeMsm.Associated:
case Wlan.WlanNotificationCodeMsm.Authenticating:
case Wlan.WlanNotificationCodeMsm.Connected:
case Wlan.WlanNotificationCodeMsm.RoamingStart:
case Wlan.WlanNotificationCodeMsm.RoamingEnd:
case Wlan.WlanNotificationCodeMsm.Disassociating:
case Wlan.WlanNotificationCodeMsm.Disconnected:
case Wlan.WlanNotificationCodeMsm.PeerJoin:
case Wlan.WlanNotificationCodeMsm.PeerLeave:
case Wlan.WlanNotificationCodeMsm.AdapterRemoval:
Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData);
if (connNotifyData.HasValue)
if (wlanIface != null)
wlanIface.OnWlanConnection(notifyData, connNotifyData.Value);
break;
}
break;
}
if (wlanIface != null)
wlanIface.OnWlanNotification(notifyData);
}
///
/// Gets the WLAN interfaces.
///
/// The WLAN interfaces.
public WlanInterface[] Interfaces
{
get
{
IntPtr ifaceList;
Wlan.ThrowIfError(
Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList));
try
{
Wlan.WlanInterfaceInfoListHeader header =
(Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader));
Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header);
WlanInterface[] interfaces = new WlanInterface[header.numberOfItems];
List currentIfaceGuids = new List();
for (int i = 0; i < header.numberOfItems; ++i)
{
Wlan.WlanInterfaceInfo info =
(Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo));
listIterator += Marshal.SizeOf(info);
WlanInterface wlanIface;
currentIfaceGuids.Add(info.interfaceGuid);
if (ifaces.ContainsKey(info.interfaceGuid))
wlanIface = ifaces[info.interfaceGuid];
else
wlanIface = new WlanInterface(this, info);
interfaces[i] = wlanIface;
ifaces[info.interfaceGuid] = wlanIface;
}
// Remove stale interfaces
Queue deadIfacesGuids = new Queue();
foreach (Guid ifaceGuid in ifaces.Keys)
{
if (!currentIfaceGuids.Contains(ifaceGuid))
deadIfacesGuids.Enqueue(ifaceGuid);
}
while(deadIfacesGuids.Count != 0)
{
Guid deadIfaceGuid = deadIfacesGuids.Dequeue();
ifaces.Remove(deadIfaceGuid);
}
return interfaces;
}
finally
{
Wlan.WlanFreeMemory(ifaceList);
}
}
}
///
/// Gets a string that describes a specified reason code.
///
/// The reason code.
/// The string.
public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode)
{
StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size
Wlan.ThrowIfError(
Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero));
return sb.ToString();
}
}
}