Function Get-BSSID { $NativeWifiCode = @' using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Net.NetworkInformation; using System.Threading; using System.Text; using System.Diagnostics; namespace NativeWifi { public static class Wlan { #region P/Invoke API /// /// Defines various opcodes used to set and query parameters for an interface. /// /// /// Corresponds to the native WLAN_INTF_OPCODE type. /// public enum WlanIntfOpcode { /// /// Opcode used to set or query whether auto config is enabled. /// AutoconfEnabled = 1, /// /// Opcode used to set or query whether background scan is enabled. /// BackgroundScanEnabled, /// /// Opcode used to set or query the media streaming mode of the driver. /// MediaStreamingMode, /// /// Opcode used to set or query the radio state. /// RadioState, /// /// Opcode used to set or query the BSS type of the interface. /// BssType, /// /// Opcode used to query the state of the interface. /// InterfaceState, /// /// Opcode used to query information about the current connection of the interface. /// CurrentConnection, /// /// Opcose used to query the current channel on which the wireless interface is operating. /// ChannelNumber, /// /// Opcode used to query the supported auth/cipher pairs for infrastructure mode. /// SupportedInfrastructureAuthCipherPairs, /// /// Opcode used to query the supported auth/cipher pairs for ad hoc mode. /// SupportedAdhocAuthCipherPairs, /// /// Opcode used to query the list of supported country or region strings. /// SupportedCountryOrRegionStringList, /// /// Opcode used to set or query the current operation mode of the wireless interface. /// CurrentOperationMode, /// /// Opcode used to query driver statistics. /// Statistics = 0x10000101, /// /// Opcode used to query the received signal strength. /// RSSI, SecurityStart = 0x20010000, SecurityEnd = 0x2fffffff, IhvStart = 0x30000000, IhvEnd = 0x3fffffff } /// /// Specifies the origin of automatic configuration (auto config) settings. /// /// /// Corresponds to the native WLAN_OPCODE_VALUE_TYPE type. /// public enum WlanOpcodeValueType { /// /// The auto config settings were queried, but the origin of the settings was not determined. /// QueryOnly = 0, /// /// The auto config settings were set by group policy. /// SetByGroupPolicy = 1, /// /// The auto config settings were set by the user. /// SetByUser = 2, /// /// The auto config settings are invalid. /// Invalid = 3 } public const uint WLAN_CLIENT_VERSION_XP_SP2 = 1; public const uint WLAN_CLIENT_VERSION_LONGHORN = 2; [DllImport("wlanapi.dll")] public static extern int WlanOpenHandle( [In] UInt32 clientVersion, [In, Out] IntPtr pReserved, [Out] out UInt32 negotiatedVersion, [Out] out IntPtr clientHandle); [DllImport("wlanapi.dll")] public static extern int WlanCloseHandle( [In] IntPtr clientHandle, [In, Out] IntPtr pReserved); [DllImport("wlanapi.dll")] public static extern int WlanEnumInterfaces( [In] IntPtr clientHandle, [In, Out] IntPtr pReserved, [Out] out IntPtr ppInterfaceList); [DllImport("wlanapi.dll")] public static extern int WlanQueryInterface( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] WlanIntfOpcode opCode, [In, Out] IntPtr pReserved, [Out] out int dataSize, [Out] out IntPtr ppData, [Out] out WlanOpcodeValueType wlanOpcodeValueType); [DllImport("wlanapi.dll")] public static extern int WlanSetInterface( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] WlanIntfOpcode opCode, [In] uint dataSize, [In] IntPtr pData, [In, Out] IntPtr pReserved); /// Not supported on Windows XP SP2: must be a null reference. /// Not supported on Windows XP SP2: must be a null reference. [DllImport("wlanapi.dll")] public static extern int WlanScan( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] IntPtr pDot11Ssid, [In] IntPtr pIeData, [In, Out] IntPtr pReserved); /// /// Defines flags passed to . /// [Flags] public enum WlanGetAvailableNetworkFlags { /// /// Include all ad-hoc network profiles in the available network list, including profiles that are not visible. /// IncludeAllAdhocProfiles = 0x00000001, /// /// Include all hidden network profiles in the available network list, including profiles that are not visible. /// IncludeAllManualHiddenProfiles = 0x00000002 } /// /// The header of an array of information about available networks. /// [StructLayout(LayoutKind.Sequential)] internal struct WlanAvailableNetworkListHeader { /// /// Contains the number of items following the header. /// public uint numberOfItems; /// /// The index of the current item. The index of the first item is 0. /// public uint index; } /// /// Contains various flags for the network. /// [Flags] public enum WlanAvailableNetworkFlags { /// /// This network is currently connected. /// Connected = 0x00000001, /// /// There is a profile for this network. /// HasProfile = 0x00000002 } /// /// Contains information about an available wireless network. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanAvailableNetwork { /// /// Contains the profile name associated with the network. /// If the network doesn't have a profile, this member will be empty. /// If multiple profiles are associated with the network, there will be multiple entries with the same SSID in the visible network list. Profile names are case-sensitive. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string profileName; /// /// Contains the SSID of the visible wireless network. /// public Dot11Ssid dot11Ssid; /// /// Specifies whether the network is infrastructure or ad hoc. /// public Dot11BssType dot11BssType; /// /// Indicates the number of BSSIDs in the network. /// public uint numberOfBssids; /// /// Indicates whether the network is connectable or not. /// public bool networkConnectable; /// /// Indicates why a network cannot be connected to. This member is only valid when is false. /// public WlanReasonCode wlanNotConnectableReason; /// /// The number of PHY types supported on available networks. /// The maximum value of this field is 8. If more than 8 PHY types are supported, must be set to true. /// private uint numberOfPhyTypes; /// /// Contains an array of values that represent the PHY types supported by the available networks. /// When is greater than 8, this array contains only the first 8 PHY types. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] private Dot11PhyType[] dot11PhyTypes; /// /// Gets the values that represent the PHY types supported by the available networks. /// public Dot11PhyType[] Dot11PhyTypes { get { Dot11PhyType[] ret = new Dot11PhyType[numberOfPhyTypes]; Array.Copy(dot11PhyTypes, ret, numberOfPhyTypes); return ret; } } /// /// Specifies if there are more than 8 PHY types supported. /// When this member is set to true, an application must call to get the complete list of PHY types. /// contains the PHY type for an entry. /// public bool morePhyTypes; /// /// A percentage value that represents the signal quality of the network. /// This field contains a value between 0 and 100. /// A value of 0 implies an actual RSSI signal strength of -100 dbm. /// A value of 100 implies an actual RSSI signal strength of -50 dbm. /// You can calculate the RSSI signal strength value for values between 1 and 99 using linear interpolation. /// public uint wlanSignalQuality; /// /// Indicates whether security is enabled on the network. /// public bool securityEnabled; /// /// Indicates the default authentication algorithm used to join this network for the first time. /// public Dot11AuthAlgorithm dot11DefaultAuthAlgorithm; /// /// Indicates the default cipher algorithm to be used when joining this network. /// public Dot11CipherAlgorithm dot11DefaultCipherAlgorithm; /// /// Contains various flags for the network. /// public WlanAvailableNetworkFlags flags; /// /// Reserved for future use. Must be set to NULL. /// uint reserved; } [DllImport("wlanapi.dll")] public static extern int WlanGetAvailableNetworkList( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] WlanGetAvailableNetworkFlags flags, [In, Out] IntPtr reservedPtr, [Out] out IntPtr availableNetworkListPtr); [Flags] public enum WlanProfileFlags { /// /// The only option available on Windows XP SP2. /// AllUser = 0, GroupPolicy = 1, User = 2 } [DllImport("wlanapi.dll")] public static extern int WlanSetProfile( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] WlanProfileFlags flags, [In, MarshalAs(UnmanagedType.LPWStr)] string profileXml, [In, Optional, MarshalAs(UnmanagedType.LPWStr)] string allUserProfileSecurity, [In] bool overwrite, [In] IntPtr pReserved, [Out] out WlanReasonCode reasonCode); /// /// Defines the access mask of an all-user profile. /// [Flags] public enum WlanAccess { /// /// The user can view profile permissions. /// ReadAccess = 0x00020000 | 0x0001, /// /// The user has read access, and the user can also connect to and disconnect from a network using the profile. /// ExecuteAccess = ReadAccess | 0x0020, /// /// The user has execute access and the user can also modify and delete permissions associated with a profile. /// WriteAccess = ReadAccess | ExecuteAccess | 0x0002 | 0x00010000 | 0x00040000 } /// Not supported on Windows XP SP2: must be a null reference. [DllImport("wlanapi.dll")] public static extern int WlanGetProfile( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In, MarshalAs(UnmanagedType.LPWStr)] string profileName, [In] IntPtr pReserved, [Out] out IntPtr profileXml, [Out, Optional] out WlanProfileFlags flags, [Out, Optional] out WlanAccess grantedAccess); [DllImport("wlanapi.dll")] public static extern int WlanGetProfileList( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] IntPtr pReserved, [Out] out IntPtr profileList ); [DllImport("wlanapi.dll")] public static extern void WlanFreeMemory(IntPtr pMemory); [DllImport("wlanapi.dll")] public static extern int WlanReasonCodeToString( [In] WlanReasonCode reasonCode, [In] int bufferSize, [In, Out] StringBuilder stringBuffer, IntPtr pReserved ); /// /// Specifies where the notification comes from. /// [Flags] public enum WlanNotificationSource { None = 0, /// /// All notifications, including those generated by the 802.1X module. /// All = 0X0000FFFF, /// /// Notifications generated by the auto configuration module. /// ACM = 0X00000008, /// /// Notifications generated by MSM. /// MSM = 0X00000010, /// /// Notifications generated by the security module. /// Security = 0X00000020, /// /// Notifications generated by independent hardware vendors (IHV). /// IHV = 0X00000040 } /// /// Indicates the type of an ACM () notification. /// /// /// The enumeration identifiers correspond to the native wlan_notification_acm_ identifiers. /// On Windows XP SP2, only the ConnectionComplete and Disconnected notifications are available. /// public enum WlanNotificationCodeAcm { AutoconfEnabled = 1, AutoconfDisabled, BackgroundScanEnabled, BackgroundScanDisabled, BssTypeChange, PowerSettingChange, ScanComplete, ScanFail, ConnectionStart, ConnectionComplete, ConnectionAttemptFail, FilterListChange, InterfaceArrival, InterfaceRemoval, ProfileChange, ProfileNameChange, ProfilesExhausted, NetworkNotAvailable, NetworkAvailable, Disconnecting, Disconnected, AdhocNetworkStateChange } /// /// Indicates the type of an MSM () notification. /// /// /// The enumeration identifiers correspond to the native wlan_notification_msm_ identifiers. /// public enum WlanNotificationCodeMsm { Associating = 1, Associated, Authenticating, Connected, RoamingStart, RoamingEnd, RadioStateChange, SignalQualityChange, Disassociating, Disconnected, PeerJoin, PeerLeave, AdapterRemoval, AdapterOperationModeChange } /// /// Contains information provided when registering for notifications. /// /// /// Corresponds to the native WLAN_NOTIFICATION_DATA type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanNotificationData { /// /// Specifies where the notification comes from. /// /// /// On Windows XP SP2, this field must be set to , or . /// public WlanNotificationSource notificationSource; /// /// Indicates the type of notification. The value of this field indicates what type of associated data will be present in . /// public int notificationCode; /// /// Indicates which interface the notification is for. /// public Guid interfaceGuid; /// /// Specifies the size of , in bytes. /// public int dataSize; /// /// Pointer to additional data needed for the notification, as indicated by . /// public IntPtr dataPtr; /// /// Gets the notification code (in the correct enumeration type) according to the notification source. /// public object NotificationCode { get { if (notificationSource == WlanNotificationSource.MSM) return (WlanNotificationCodeMsm)notificationCode; else if (notificationSource == WlanNotificationSource.ACM) return (WlanNotificationCodeAcm)notificationCode; else return notificationCode; } } } /// /// Defines the callback function which accepts WLAN notifications. /// public delegate void WlanNotificationCallbackDelegate(ref WlanNotificationData notificationData, IntPtr context); [DllImport("wlanapi.dll")] public static extern int WlanRegisterNotification( [In] IntPtr clientHandle, [In] WlanNotificationSource notifSource, [In] bool ignoreDuplicate, [In] WlanNotificationCallbackDelegate funcCallback, [In] IntPtr callbackContext, [In] IntPtr reserved, [Out] out WlanNotificationSource prevNotifSource); /// /// Defines connection parameter flags. /// [Flags] public enum WlanConnectionFlags { /// /// Connect to the destination network even if the destination is a hidden network. A hidden network does not broadcast its SSID. Do not use this flag if the destination network is an ad-hoc network. /// If the profile specified by is not null, then this flag is ignored and the nonBroadcast profile element determines whether to connect to a hidden network. /// HiddenNetwork = 0x00000001, /// /// Do not form an ad-hoc network. Only join an ad-hoc network if the network already exists. Do not use this flag if the destination network is an infrastructure network. /// AdhocJoinOnly = 0x00000002, /// /// Ignore the privacy bit when connecting to the network. Ignoring the privacy bit has the effect of ignoring whether packets are encryption and ignoring the method of encryption used. Only use this flag when connecting to an infrastructure network using a temporary profile. /// IgnorePrivacyBit = 0x00000004, /// /// Exempt EAPOL traffic from encryption and decryption. This flag is used when an application must send EAPOL traffic over an infrastructure network that uses Open authentication and WEP encryption. This flag must not be used to connect to networks that require 802.1X authentication. This flag is only valid when is set to . Avoid using this flag whenever possible. /// EapolPassthrough = 0x00000008 } /// /// Specifies the parameters used when using the function. /// /// /// Corresponds to the native WLAN_CONNECTION_PARAMETERS type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanConnectionParameters { /// /// Specifies the mode of connection. /// public WlanConnectionMode wlanConnectionMode; /// /// Specifies the profile being used for the connection. /// The contents of the field depend on the : /// /// /// Value of /// Contents of the profile string /// /// /// /// The name of the profile used for the connection. /// /// /// /// The XML representation of the profile used for the connection. /// /// /// , or /// null /// /// /// [MarshalAs(UnmanagedType.LPWStr)] public string profile; /// /// Pointer to a structure that specifies the SSID of the network to connect to. /// This field is optional. When set to null, all SSIDs in the profile will be tried. /// This field must not be null if is set to or . /// public IntPtr dot11SsidPtr; /// /// Pointer to a structure that contains the list of basic service set (BSS) identifiers desired for the connection. /// /// /// On Windows XP SP2, must be set to null. /// public IntPtr desiredBssidListPtr; /// /// A value that indicates the BSS type of the network. If a profile is provided, this BSS type must be the same as the one in the profile. /// public Dot11BssType dot11BssType; /// /// Specifies ocnnection parameters. /// /// /// On Windows XP SP2, must be set to 0. /// public WlanConnectionFlags flags; } /// /// The connection state of an ad hoc network. /// public enum WlanAdhocNetworkState { /// /// The ad hoc network has been formed, but no client or host is connected to the network. /// Formed = 0, /// /// A client or host is connected to the ad hoc network. /// Connected = 1 } [DllImport("wlanapi.dll")] public static extern int WlanConnect( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] ref WlanConnectionParameters connectionParameters, IntPtr pReserved); [DllImport("wlanapi.dll")] public static extern int WlanDeleteProfile( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In, MarshalAs(UnmanagedType.LPWStr)] string profileName, IntPtr reservedPtr ); [DllImport("wlanapi.dll")] public static extern int WlanGetNetworkBssList( [In] IntPtr clientHandle, [In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, [In] IntPtr dot11SsidInt, [In] Dot11BssType dot11BssType, [In] bool securityEnabled, IntPtr reservedPtr, [Out] out IntPtr wlanBssList ); [StructLayout(LayoutKind.Sequential)] internal struct WlanBssListHeader { internal uint totalSize; internal uint numberOfItems; } /// /// Contains information about a basic service set (BSS). /// [StructLayout(LayoutKind.Sequential)] public struct WlanBssEntry { /// /// Contains the SSID of the access point (AP) associated with the BSS. /// public Dot11Ssid dot11Ssid; /// /// The identifier of the PHY on which the AP is operating. /// public uint phyId; /// /// Contains the BSS identifier. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public byte[] dot11Bssid; /// /// Specifies whether the network is infrastructure or ad hoc. /// public Dot11BssType dot11BssType; public Dot11PhyType dot11BssPhyType; /// /// The received signal strength in dBm. /// public int rssi; /// /// The link quality reported by the driver. Ranges from 0-100. /// public uint linkQuality; /// /// If 802.11d is not implemented, the network interface card (NIC) must set this field to TRUE. If 802.11d is implemented (but not necessarily enabled), the NIC must set this field to TRUE if the BSS operation complies with the configured regulatory domain. /// public bool inRegDomain; /// /// Contains the beacon interval value from the beacon packet or probe response. /// public ushort beaconPeriod; /// /// The timestamp from the beacon packet or probe response. /// public ulong timestamp; /// /// The host timestamp value when the beacon or probe response is received. /// public ulong hostTimestamp; /// /// The capability value from the beacon packet or probe response. /// public ushort capabilityInformation; /// /// The frequency of the center channel, in kHz. /// public uint chCenterFrequency; /// /// Contains the set of data transfer rates supported by the BSS. /// public WlanRateSet wlanRateSet; /// /// Offset of the information element (IE) data blob. /// public uint ieOffset; /// /// Size of the IE data blob, in bytes. /// public uint ieSize; } /// /// Contains the set of supported data rates. /// [StructLayout(LayoutKind.Sequential)] public struct WlanRateSet { /// /// The length, in bytes, of . /// private uint rateSetLength; /// /// An array of supported data transfer rates. /// If the rate is a basic rate, the first bit of the rate value is set to 1. /// A basic rate is the data transfer rate that all stations in a basic service set (BSS) can use to receive frames from the wireless medium. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 126)] private ushort[] rateSet; public ushort[] Rates { get { ushort[] rates = new ushort[rateSetLength / sizeof(ushort)]; Array.Copy(rateSet, rates, rates.Length); return rates; } } /// /// CalculateS the data transfer rate in Mbps for an arbitrary supported rate. /// /// /// public double GetRateInMbps(int rate) { return (rateSet[rate] & 0x7FFF) * 0.5; } } /// /// Represents an error occuring during WLAN operations which indicate their failure via a . /// public class WlanException : Exception { private WlanReasonCode reasonCode; WlanException(WlanReasonCode reasonCode) { this.reasonCode = reasonCode; } /// /// Gets the WLAN reason code. /// /// The WLAN reason code. public WlanReasonCode ReasonCode { get { return reasonCode; } } /// /// Gets a message that describes the reason code. /// /// /// The error message that explains the reason for the exception, or an empty string(""). public override string Message { get { StringBuilder sb = new StringBuilder(1024); if (WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero) == 0) return sb.ToString(); else return string.Empty; } } } // TODO: .NET-ify the WlanReasonCode enum (naming convention + docs). /// /// Specifies reasons for a failure of a WLAN operation. /// /// /// To get the WLAN API native reason code identifiers, prefix the identifiers with WLAN_REASON_CODE_. /// public enum WlanReasonCode { Success = 0, // general codes UNKNOWN = 0x10000 + 1, RANGE_SIZE = 0x10000, BASE = 0x10000 + RANGE_SIZE, // range for Auto Config // AC_BASE = 0x10000 + RANGE_SIZE, AC_CONNECT_BASE = (AC_BASE + RANGE_SIZE / 2), AC_END = (AC_BASE + RANGE_SIZE - 1), // range for profile manager // it has profile adding failure reason codes, but may not have // connection reason codes // PROFILE_BASE = 0x10000 + (7 * RANGE_SIZE), PROFILE_CONNECT_BASE = (PROFILE_BASE + RANGE_SIZE / 2), PROFILE_END = (PROFILE_BASE + RANGE_SIZE - 1), // range for MSM // MSM_BASE = 0x10000 + (2 * RANGE_SIZE), MSM_CONNECT_BASE = (MSM_BASE + RANGE_SIZE / 2), MSM_END = (MSM_BASE + RANGE_SIZE - 1), // range for MSMSEC // MSMSEC_BASE = 0x10000 + (3 * RANGE_SIZE), MSMSEC_CONNECT_BASE = (MSMSEC_BASE + RANGE_SIZE / 2), MSMSEC_END = (MSMSEC_BASE + RANGE_SIZE - 1), // AC network incompatible reason codes // NETWORK_NOT_COMPATIBLE = (AC_BASE + 1), PROFILE_NOT_COMPATIBLE = (AC_BASE + 2), // AC connect reason code // NO_AUTO_CONNECTION = (AC_CONNECT_BASE + 1), NOT_VISIBLE = (AC_CONNECT_BASE + 2), GP_DENIED = (AC_CONNECT_BASE + 3), USER_DENIED = (AC_CONNECT_BASE + 4), BSS_TYPE_NOT_ALLOWED = (AC_CONNECT_BASE + 5), IN_FAILED_LIST = (AC_CONNECT_BASE + 6), IN_BLOCKED_LIST = (AC_CONNECT_BASE + 7), SSID_LIST_TOO_LONG = (AC_CONNECT_BASE + 8), CONNECT_CALL_FAIL = (AC_CONNECT_BASE + 9), SCAN_CALL_FAIL = (AC_CONNECT_BASE + 10), NETWORK_NOT_AVAILABLE = (AC_CONNECT_BASE + 11), PROFILE_CHANGED_OR_DELETED = (AC_CONNECT_BASE + 12), KEY_MISMATCH = (AC_CONNECT_BASE + 13), USER_NOT_RESPOND = (AC_CONNECT_BASE + 14), // Profile validation errors // INVALID_PROFILE_SCHEMA = (PROFILE_BASE + 1), PROFILE_MISSING = (PROFILE_BASE + 2), INVALID_PROFILE_NAME = (PROFILE_BASE + 3), INVALID_PROFILE_TYPE = (PROFILE_BASE + 4), INVALID_PHY_TYPE = (PROFILE_BASE + 5), MSM_SECURITY_MISSING = (PROFILE_BASE + 6), IHV_SECURITY_NOT_SUPPORTED = (PROFILE_BASE + 7), IHV_OUI_MISMATCH = (PROFILE_BASE + 8), // IHV OUI not present but there is IHV settings in profile IHV_OUI_MISSING = (PROFILE_BASE + 9), // IHV OUI is present but there is no IHV settings in profile IHV_SETTINGS_MISSING = (PROFILE_BASE + 10), // both/conflict MSMSec and IHV security settings exist in profile CONFLICT_SECURITY = (PROFILE_BASE + 11), // no IHV or MSMSec security settings in profile SECURITY_MISSING = (PROFILE_BASE + 12), INVALID_BSS_TYPE = (PROFILE_BASE + 13), INVALID_ADHOC_CONNECTION_MODE = (PROFILE_BASE + 14), NON_BROADCAST_SET_FOR_ADHOC = (PROFILE_BASE + 15), AUTO_SWITCH_SET_FOR_ADHOC = (PROFILE_BASE + 16), AUTO_SWITCH_SET_FOR_MANUAL_CONNECTION = (PROFILE_BASE + 17), IHV_SECURITY_ONEX_MISSING = (PROFILE_BASE + 18), PROFILE_SSID_INVALID = (PROFILE_BASE + 19), TOO_MANY_SSID = (PROFILE_BASE + 20), // MSM network incompatible reasons // UNSUPPORTED_SECURITY_SET_BY_OS = (MSM_BASE + 1), UNSUPPORTED_SECURITY_SET = (MSM_BASE + 2), BSS_TYPE_UNMATCH = (MSM_BASE + 3), PHY_TYPE_UNMATCH = (MSM_BASE + 4), DATARATE_UNMATCH = (MSM_BASE + 5), // MSM connection failure reasons, to be defined // failure reason codes // // user called to disconnect USER_CANCELLED = (MSM_CONNECT_BASE + 1), // got disconnect while associating ASSOCIATION_FAILURE = (MSM_CONNECT_BASE + 2), // timeout for association ASSOCIATION_TIMEOUT = (MSM_CONNECT_BASE + 3), // pre-association security completed with failure PRE_SECURITY_FAILURE = (MSM_CONNECT_BASE + 4), // fail to start post-association security START_SECURITY_FAILURE = (MSM_CONNECT_BASE + 5), // post-association security completed with failure SECURITY_FAILURE = (MSM_CONNECT_BASE + 6), // security watchdog timeout SECURITY_TIMEOUT = (MSM_CONNECT_BASE + 7), // got disconnect from driver when roaming ROAMING_FAILURE = (MSM_CONNECT_BASE + 8), // failed to start security for roaming ROAMING_SECURITY_FAILURE = (MSM_CONNECT_BASE + 9), // failed to start security for adhoc-join ADHOC_SECURITY_FAILURE = (MSM_CONNECT_BASE + 10), // got disconnection from driver DRIVER_DISCONNECTED = (MSM_CONNECT_BASE + 11), // driver operation failed DRIVER_OPERATION_FAILURE = (MSM_CONNECT_BASE + 12), // Ihv service is not available IHV_NOT_AVAILABLE = (MSM_CONNECT_BASE + 13), // Response from ihv timed out IHV_NOT_RESPONDING = (MSM_CONNECT_BASE + 14), // Timed out waiting for driver to disconnect DISCONNECT_TIMEOUT = (MSM_CONNECT_BASE + 15), // An internal error prevented the operation from being completed. INTERNAL_FAILURE = (MSM_CONNECT_BASE + 16), // UI Request timed out. UI_REQUEST_TIMEOUT = (MSM_CONNECT_BASE + 17), // Roaming too often, post security is not completed after 5 times. TOO_MANY_SECURITY_ATTEMPTS = (MSM_CONNECT_BASE + 18), // MSMSEC reason codes // MSMSEC_MIN = MSMSEC_BASE, // Key index specified is not valid MSMSEC_PROFILE_INVALID_KEY_INDEX = (MSMSEC_BASE + 1), // Key required, PSK present MSMSEC_PROFILE_PSK_PRESENT = (MSMSEC_BASE + 2), // Invalid key length MSMSEC_PROFILE_KEY_LENGTH = (MSMSEC_BASE + 3), // Invalid PSK length MSMSEC_PROFILE_PSK_LENGTH = (MSMSEC_BASE + 4), // No auth/cipher specified MSMSEC_PROFILE_NO_AUTH_CIPHER_SPECIFIED = (MSMSEC_BASE + 5), // Too many auth/cipher specified MSMSEC_PROFILE_TOO_MANY_AUTH_CIPHER_SPECIFIED = (MSMSEC_BASE + 6), // Profile contains duplicate auth/cipher MSMSEC_PROFILE_DUPLICATE_AUTH_CIPHER = (MSMSEC_BASE + 7), // Profile raw data is invalid (1x or key data) MSMSEC_PROFILE_RAWDATA_INVALID = (MSMSEC_BASE + 8), // Invalid auth/cipher combination MSMSEC_PROFILE_INVALID_AUTH_CIPHER = (MSMSEC_BASE + 9), // 802.1x disabled when it's required to be enabled MSMSEC_PROFILE_ONEX_DISABLED = (MSMSEC_BASE + 10), // 802.1x enabled when it's required to be disabled MSMSEC_PROFILE_ONEX_ENABLED = (MSMSEC_BASE + 11), MSMSEC_PROFILE_INVALID_PMKCACHE_MODE = (MSMSEC_BASE + 12), MSMSEC_PROFILE_INVALID_PMKCACHE_SIZE = (MSMSEC_BASE + 13), MSMSEC_PROFILE_INVALID_PMKCACHE_TTL = (MSMSEC_BASE + 14), MSMSEC_PROFILE_INVALID_PREAUTH_MODE = (MSMSEC_BASE + 15), MSMSEC_PROFILE_INVALID_PREAUTH_THROTTLE = (MSMSEC_BASE + 16), // PreAuth enabled when PMK cache is disabled MSMSEC_PROFILE_PREAUTH_ONLY_ENABLED = (MSMSEC_BASE + 17), // Capability matching failed at network MSMSEC_CAPABILITY_NETWORK = (MSMSEC_BASE + 18), // Capability matching failed at NIC MSMSEC_CAPABILITY_NIC = (MSMSEC_BASE + 19), // Capability matching failed at profile MSMSEC_CAPABILITY_PROFILE = (MSMSEC_BASE + 20), // Network does not support specified discovery type MSMSEC_CAPABILITY_DISCOVERY = (MSMSEC_BASE + 21), // Passphrase contains invalid character MSMSEC_PROFILE_PASSPHRASE_CHAR = (MSMSEC_BASE + 22), // Key material contains invalid character MSMSEC_PROFILE_KEYMATERIAL_CHAR = (MSMSEC_BASE + 23), // Wrong key type specified for the auth/cipher pair MSMSEC_PROFILE_WRONG_KEYTYPE = (MSMSEC_BASE + 24), // "Mixed cell" suspected (AP not beaconing privacy, we have privacy enabled profile) MSMSEC_MIXED_CELL = (MSMSEC_BASE + 25), // Auth timers or number of timeouts in profile is incorrect MSMSEC_PROFILE_AUTH_TIMERS_INVALID = (MSMSEC_BASE + 26), // Group key update interval in profile is incorrect MSMSEC_PROFILE_INVALID_GKEY_INTV = (MSMSEC_BASE + 27), // "Transition network" suspected, trying legacy 802.11 security MSMSEC_TRANSITION_NETWORK = (MSMSEC_BASE + 28), // Key contains characters which do not map to ASCII MSMSEC_PROFILE_KEY_UNMAPPED_CHAR = (MSMSEC_BASE + 29), // Capability matching failed at profile (auth not found) MSMSEC_CAPABILITY_PROFILE_AUTH = (MSMSEC_BASE + 30), // Capability matching failed at profile (cipher not found) MSMSEC_CAPABILITY_PROFILE_CIPHER = (MSMSEC_BASE + 31), // Failed to queue UI request MSMSEC_UI_REQUEST_FAILURE = (MSMSEC_CONNECT_BASE + 1), // 802.1x authentication did not start within configured time MSMSEC_AUTH_START_TIMEOUT = (MSMSEC_CONNECT_BASE + 2), // 802.1x authentication did not complete within configured time MSMSEC_AUTH_SUCCESS_TIMEOUT = (MSMSEC_CONNECT_BASE + 3), // Dynamic key exchange did not start within configured time MSMSEC_KEY_START_TIMEOUT = (MSMSEC_CONNECT_BASE + 4), // Dynamic key exchange did not succeed within configured time MSMSEC_KEY_SUCCESS_TIMEOUT = (MSMSEC_CONNECT_BASE + 5), // Message 3 of 4 way handshake has no key data (RSN/WPA) MSMSEC_M3_MISSING_KEY_DATA = (MSMSEC_CONNECT_BASE + 6), // Message 3 of 4 way handshake has no IE (RSN/WPA) MSMSEC_M3_MISSING_IE = (MSMSEC_CONNECT_BASE + 7), // Message 3 of 4 way handshake has no Group Key (RSN) MSMSEC_M3_MISSING_GRP_KEY = (MSMSEC_CONNECT_BASE + 8), // Matching security capabilities of IE in M3 failed (RSN/WPA) MSMSEC_PR_IE_MATCHING = (MSMSEC_CONNECT_BASE + 9), // Matching security capabilities of Secondary IE in M3 failed (RSN) MSMSEC_SEC_IE_MATCHING = (MSMSEC_CONNECT_BASE + 10), // Required a pairwise key but AP configured only group keys MSMSEC_NO_PAIRWISE_KEY = (MSMSEC_CONNECT_BASE + 11), // Message 1 of group key handshake has no key data (RSN/WPA) MSMSEC_G1_MISSING_KEY_DATA = (MSMSEC_CONNECT_BASE + 12), // Message 1 of group key handshake has no group key MSMSEC_G1_MISSING_GRP_KEY = (MSMSEC_CONNECT_BASE + 13), // AP reset secure bit after connection was secured MSMSEC_PEER_INDICATED_INSECURE = (MSMSEC_CONNECT_BASE + 14), // 802.1x indicated there is no authenticator but profile requires 802.1x MSMSEC_NO_AUTHENTICATOR = (MSMSEC_CONNECT_BASE + 15), // Plumbing settings to NIC failed MSMSEC_NIC_FAILURE = (MSMSEC_CONNECT_BASE + 16), // Operation was cancelled by caller MSMSEC_CANCELLED = (MSMSEC_CONNECT_BASE + 17), // Key was in incorrect format MSMSEC_KEY_FORMAT = (MSMSEC_CONNECT_BASE + 18), // Security downgrade detected MSMSEC_DOWNGRADE_DETECTED = (MSMSEC_CONNECT_BASE + 19), // PSK mismatch suspected MSMSEC_PSK_MISMATCH_SUSPECTED = (MSMSEC_CONNECT_BASE + 20), // Forced failure because connection method was not secure MSMSEC_FORCED_FAILURE = (MSMSEC_CONNECT_BASE + 21), // ui request couldn't be queued or user pressed cancel MSMSEC_SECURITY_UI_FAILURE = (MSMSEC_CONNECT_BASE + 22), MSMSEC_MAX = MSMSEC_END } /// /// Contains information about connection related notifications. /// /// /// Corresponds to the native WLAN_CONNECTION_NOTIFICATION_DATA type. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanConnectionNotificationData { /// /// On Windows XP SP 2, only is supported. /// public WlanConnectionMode wlanConnectionMode; /// /// The name of the profile used for the connection. Profile names are case-sensitive. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string profileName; /// /// The SSID of the association. /// public Dot11Ssid dot11Ssid; /// /// The BSS network type. /// public Dot11BssType dot11BssType; /// /// Indicates whether security is enabled for this connection. /// public bool securityEnabled; /// /// Indicates the reason for an operation failure. /// This field has a value of for all connection-related notifications except . /// If the connection fails, this field indicates the reason for the failure. /// public WlanReasonCode wlanReasonCode; /// /// This field contains the XML presentation of the profile used for discovery, if the connection succeeds. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1)] public string profileXml; } /// /// Indicates the state of an interface. /// /// /// Corresponds to the native WLAN_INTERFACE_STATE type. /// public enum WlanInterfaceState { /// /// The interface is not ready to operate. /// NotReady = 0, /// /// The interface is connected to a network. /// Connected = 1, /// /// The interface is the first node in an ad hoc network. No peer has connected. /// AdHocNetworkFormed = 2, /// /// The interface is disconnecting from the current network. /// Disconnecting = 3, /// /// The interface is not connected to any network. /// Disconnected = 4, /// /// The interface is attempting to associate with a network. /// Associating = 5, /// /// Auto configuration is discovering the settings for the network. /// Discovering = 6, /// /// The interface is in the process of authenticating. /// Authenticating = 7 } /// /// Contains the SSID of an interface. /// public struct Dot11Ssid { /// /// The length, in bytes, of the array. /// public uint SSIDLength; /// /// The SSID. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] SSID; } /// /// Defines an 802.11 PHY and media type. /// /// /// Corresponds to the native DOT11_PHY_TYPE type. /// public enum Dot11PhyType : uint { /// /// Specifies an unknown or uninitialized PHY type. /// Unknown = 0, /// /// Specifies any PHY type. /// Any = Unknown, /// /// Specifies a frequency-hopping spread-spectrum (FHSS) PHY. Bluetooth devices can use FHSS or an adaptation of FHSS. /// FHSS = 1, /// /// Specifies a direct sequence spread spectrum (DSSS) PHY. /// DSSS = 2, /// /// Specifies an infrared (IR) baseband PHY. /// IrBaseband = 3, /// /// Specifies an orthogonal frequency division multiplexing (OFDM) PHY. 802.11a devices can use OFDM. /// OFDM = 4, /// /// Specifies a high-rate DSSS (HRDSSS) PHY. /// HRDSSS = 5, /// /// Specifies an extended rate PHY (ERP). 802.11g devices can use ERP. /// ERP = 6, /// /// Specifies the start of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). /// IHV_Start = 0x80000000, /// /// Specifies the end of the range that is used to define PHY types that are developed by an independent hardware vendor (IHV). /// IHV_End = 0xffffffff } /// /// Defines a basic service set (BSS) network type. /// /// /// Corresponds to the native DOT11_BSS_TYPE type. /// public enum Dot11BssType { /// /// Specifies an infrastructure BSS network. /// Infrastructure = 1, /// /// Specifies an independent BSS (IBSS) network. /// Independent = 2, /// /// Specifies either infrastructure or IBSS network. /// Any = 3 } /// /// Contains association attributes for a connection /// /// /// Corresponds to the native WLAN_ASSOCIATION_ATTRIBUTES type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanAssociationAttributes { /// /// The SSID of the association. /// public Dot11Ssid dot11Ssid; /// /// Specifies whether the network is infrastructure or ad hoc. /// public Dot11BssType dot11BssType; /// /// The BSSID of the association. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)] public byte[] dot11Bssid; /// /// The physical type of the association. /// public Dot11PhyType dot11PhyType; /// /// The position of the value in the structure containing the list of PHY types. /// public uint dot11PhyIndex; /// /// A percentage value that represents the signal quality of the network. /// This field contains a value between 0 and 100. /// A value of 0 implies an actual RSSI signal strength of -100 dbm. /// A value of 100 implies an actual RSSI signal strength of -50 dbm. /// You can calculate the RSSI signal strength value for values between 1 and 99 using linear interpolation. /// public uint wlanSignalQuality; /// /// The receiving rate of the association. /// public uint rxRate; /// /// The transmission rate of the association. /// public uint txRate; /// /// Gets the BSSID of the associated access point. /// /// The BSSID. public PhysicalAddress Dot11Bssid { get { return new PhysicalAddress(dot11Bssid); } } } /// /// Defines the mode of connection. /// /// /// Corresponds to the native WLAN_CONNECTION_MODE type. /// public enum WlanConnectionMode { /// /// A profile will be used to make the connection. /// Profile = 0, /// /// A temporary profile will be used to make the connection. /// TemporaryProfile, /// /// Secure discovery will be used to make the connection. /// DiscoverySecure, /// /// Unsecure discovery will be used to make the connection. /// DiscoveryUnsecure, /// /// A connection will be made automatically, generally using a persistent profile. /// Auto, /// /// Not used. /// Invalid } /// /// Defines a wireless LAN authentication algorithm. /// /// /// Corresponds to the native DOT11_AUTH_ALGORITHM type. /// public enum Dot11AuthAlgorithm : uint { /// /// Specifies an IEEE 802.11 Open System authentication algorithm. /// IEEE80211_Open = 1, /// /// Specifies an 802.11 Shared Key authentication algorithm that requires the use of a pre-shared Wired Equivalent Privacy (WEP) key for the 802.11 authentication. /// IEEE80211_SharedKey = 2, /// /// Specifies a Wi-Fi Protected Access (WPA) algorithm. IEEE 802.1X port authentication is performed by the supplicant, authenticator, and authentication server. Cipher keys are dynamically derived through the authentication process. /// This algorithm is valid only for BSS types of . /// When the WPA algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 1 (802.1X) within the WPA information element (IE). /// WPA = 3, /// /// Specifies a WPA algorithm that uses preshared keys (PSK). IEEE 802.1X port authentication is performed by the supplicant and authenticator. Cipher keys are dynamically derived through a preshared key that is used on both the supplicant and authenticator. /// This algorithm is valid only for BSS types of . /// When the WPA PSK algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 2 (preshared key) within the WPA IE. /// WPA_PSK = 4, /// /// This value is not supported. /// WPA_None = 5, /// /// Specifies an 802.11i Robust Security Network Association (RSNA) algorithm. WPA2 is one such algorithm. IEEE 802.1X port authentication is performed by the supplicant, authenticator, and authentication server. Cipher keys are dynamically derived through the authentication process. /// This algorithm is valid only for BSS types of . /// When the RSNA algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 1 (802.1X) within the RSN IE. /// RSNA = 6, /// /// Specifies an 802.11i RSNA algorithm that uses PSK. IEEE 802.1X port authentication is performed by the supplicant and authenticator. Cipher keys are dynamically derived through a preshared key that is used on both the supplicant and authenticator. /// This algorithm is valid only for BSS types of . /// When the RSNA PSK algorithm is enabled, the 802.11 station will associate only with an access point whose beacon or probe responses contain the authentication suite of type 2(preshared key) within the RSN IE. /// RSNA_PSK = 7, /// /// Indicates the start of the range that specifies proprietary authentication algorithms that are developed by an IHV. /// /// /// This enumerator is valid only when the miniport driver is operating in Extensible Station (ExtSTA) mode. /// IHV_Start = 0x80000000, /// /// Indicates the end of the range that specifies proprietary authentication algorithms that are developed by an IHV. /// /// /// This enumerator is valid only when the miniport driver is operating in Extensible Station (ExtSTA) mode. /// IHV_End = 0xffffffff } /// /// Defines a cipher algorithm for data encryption and decryption. /// /// /// Corresponds to the native DOT11_CIPHER_ALGORITHM type. /// public enum Dot11CipherAlgorithm : uint { /// /// Specifies that no cipher algorithm is enabled or supported. /// None = 0x00, /// /// Specifies a Wired Equivalent Privacy (WEP) algorithm, which is the RC4-based algorithm that is specified in the 802.11-1999 standard. This enumerator specifies the WEP cipher algorithm with a 40-bit cipher key. /// WEP40 = 0x01, /// /// Specifies a Temporal Key Integrity Protocol (TKIP) algorithm, which is the RC4-based cipher suite that is based on the algorithms that are defined in the WPA specification and IEEE 802.11i-2004 standard. This cipher also uses the Michael Message Integrity Code (MIC) algorithm for forgery protection. /// TKIP = 0x02, /// /// Specifies an AES-CCMP algorithm, as specified in the IEEE 802.11i-2004 standard and RFC 3610. Advanced Encryption Standard (AES) is the encryption algorithm defined in FIPS PUB 197. /// CCMP = 0x04, /// /// Specifies a WEP cipher algorithm with a 104-bit cipher key. /// WEP104 = 0x05, /// /// Specifies a Robust Security Network (RSN) Use Group Key cipher suite. For more information about the Use Group Key cipher suite, refer to Clause 7.3.2.9.1 of the IEEE 802.11i-2004 standard. /// WPA_UseGroup = 0x100, /// /// Specifies a Wifi Protected Access (WPA) Use Group Key cipher suite. For more information about the Use Group Key cipher suite, refer to Clause 7.3.2.9.1 of the IEEE 802.11i-2004 standard. /// RSN_UseGroup = 0x100, /// /// Specifies a WEP cipher algorithm with a cipher key of any length. /// WEP = 0x101, /// /// Specifies the start of the range that is used to define proprietary cipher algorithms that are developed by an independent hardware vendor (IHV). /// IHV_Start = 0x80000000, /// /// Specifies the end of the range that is used to define proprietary cipher algorithms that are developed by an IHV. /// IHV_End = 0xffffffff } /// /// Defines the security attributes for a wireless connection. /// /// /// Corresponds to the native WLAN_SECURITY_ATTRIBUTES type. /// [StructLayout(LayoutKind.Sequential)] public struct WlanSecurityAttributes { /// /// Indicates whether security is enabled for this connection. /// [MarshalAs(UnmanagedType.Bool)] public bool securityEnabled; [MarshalAs(UnmanagedType.Bool)] public bool oneXEnabled; /// /// The authentication algorithm. /// public Dot11AuthAlgorithm dot11AuthAlgorithm; /// /// The cipher algorithm. /// public Dot11CipherAlgorithm dot11CipherAlgorithm; } /// /// Defines the attributes of a wireless connection. /// /// /// Corresponds to the native WLAN_CONNECTION_ATTRIBUTES type. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanConnectionAttributes { /// /// The state of the interface. /// public WlanInterfaceState isState; /// /// The mode of the connection. /// public WlanConnectionMode wlanConnectionMode; /// /// The name of the profile used for the connection. Profile names are case-sensitive. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string profileName; /// /// The attributes of the association. /// public WlanAssociationAttributes wlanAssociationAttributes; /// /// The security attributes of the connection. /// public WlanSecurityAttributes wlanSecurityAttributes; } /// /// Contains information about a LAN interface. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanInterfaceInfo { /// /// The GUID of the interface. /// public Guid interfaceGuid; /// /// The description of the interface. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string interfaceDescription; /// /// The current state of the interface. /// public WlanInterfaceState isState; } /// /// The header of the list returned by . /// [StructLayout(LayoutKind.Sequential)] internal struct WlanInterfaceInfoListHeader { public uint numberOfItems; public uint index; } /// /// The header of the list returned by . /// [StructLayout(LayoutKind.Sequential)] internal struct WlanProfileInfoListHeader { public uint numberOfItems; public uint index; } /// /// Contains basic information about a profile. /// [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct WlanProfileInfo { /// /// The name of the profile. This value may be the name of a domain if the profile is for provisioning. Profile names are case-sensitive. /// [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string profileName; /// /// Profile flags. /// public WlanProfileFlags profileFlags; } /// /// Flags that specifiy the miniport driver's current operation mode. /// [Flags] public enum Dot11OperationMode : uint { Unknown = 0x00000000, Station = 0x00000001, AP = 0x00000002, /// /// Specifies that the miniport driver supports the Extensible Station (ExtSTA) operation mode. /// ExtensibleStation = 0x00000004, /// /// Specifies that the miniport driver supports the Network Monitor (NetMon) operation mode. /// NetworkMonitor = 0x80000000 } #endregion /// /// Helper method to wrap calls to Native WiFi API methods. /// If the method falls, throws an exception containing the error code. /// /// The error code. [DebuggerStepThrough] internal static void ThrowIfError(int win32ErrorCode) { if (win32ErrorCode != 0) throw new Win32Exception(win32ErrorCode); } } /// /// 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(); } } } '@ function Convert-ByteArrayToString { [CmdletBinding()] Param ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray ) $Encoding = New-Object System.Text.ASCIIEncoding $Encoding.GetString($ByteArray) } Add-Type $NativeWifiCode $WlanClient = New-Object NativeWifi.WlanClient $WlanClient.Interfaces | ForEach-Object { $_.GetNetworkBssList() } | Select-Object *,@{Name="SSID";Expression={(Convert-ByteArrayToString -ByteArray $_.dot11ssid.SSID).substring(0,$_.dot11ssid.SSIDlength)}} | Select-Object ssid,phyId,rssi,linkQuality,timestamp }