Beispiel #1
0
        /// <summary>
        /// Gets the information of all profiles on this interface.
        /// </summary>
        /// <returns>The profiles information.</returns>
        public WlanProfileInfo[] GetProfiles()
        {
            IntPtr profileListPtr;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr));

            try
            {
                WlanProfileInfoListHeader header       = (WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(WlanProfileInfoListHeader));
                WlanProfileInfo[]         profileInfos = new WlanProfileInfo[header.numberOfItems];
                long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header);

                for (int i = 0; i < header.numberOfItems; ++i)
                {
                    WlanProfileInfo profileInfo = (WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(WlanProfileInfo));
                    profileInfos[i]      = profileInfo;
                    profileListIterator += Marshal.SizeOf(profileInfo);
                }

                return(profileInfos);
            }
            finally
            {
                WlanInterop.WlanFreeMemory(profileListPtr);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Turn off WiFi.
        /// </summary>
        public void TurnOffWiFi()
        {
            IntPtr radioStatePtr = IntPtr.Zero;

            try
            {
                WlanPhyRadioState radioState = new WlanPhyRadioState
                {
                    dwPhyIndex = 0,
                    dot11HardwareRadioState = Dot11RadioState.Off,
                    dot11SoftwareRadioState = Dot11RadioState.Off
                };

                radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
                Marshal.StructureToPtr(radioState, radioStatePtr, false);

                WlanInterop.ThrowIfError(WlanInterop.WlanSetInterface(
                                             client.clientHandle,
                                             info.interfaceGuid,
                                             WlanIntfOpcode.RadioState,
                                             (uint)Marshal.SizeOf(typeof(WlanPhyRadioState)),
                                             radioStatePtr,
                                             IntPtr.Zero));
            }
            finally
            {
                Marshal.FreeHGlobal(radioStatePtr);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Gets the information of all profiles on this interface.
        /// </summary>
        /// <returns>The profiles information.</returns>
        public string[] GetProfilesXml(bool isProtected)
        {
            IntPtr profileListPtr;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetProfileList(_client.ClientHandle, _info.interfaceGuid, IntPtr.Zero, out profileListPtr));

            try
            {
                WlanProfileInfoListHeader header = (WlanProfileInfoListHeader)Marshal.PtrToStructure(profileListPtr, typeof(WlanProfileInfoListHeader));
                string[] profileInfos            = new string[header.numberOfItems];
                long     profileListIterator     = profileListPtr.ToInt64() + Marshal.SizeOf(header);

                for (int i = 0; i < header.numberOfItems; ++i)
                {
                    WlanProfileInfo profileInfo = (WlanProfileInfo)Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(WlanProfileInfo));
                    profileInfos[i]      = this.GetProfileXml(profileInfo.profileName, isProtected);
                    profileListIterator += Marshal.SizeOf(profileInfo);
                }

                return(profileInfos);
            }
            finally
            {
                WlanInterop.WlanFreeMemory(profileListPtr);
            }
        }
Beispiel #4
0
        /// <summary>
        /// Retrieves the basic service sets (BSS) list of the specified network.
        /// </summary>
        /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param>
        /// <param name="bssType">Indicates the BSS type of the network.</param>
        /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param>
        public WlanBssEntry[] GetNetworkBssList(Dot11Ssid ssid, Dot11BssType bssType, bool securityEnabled)
        {
            IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid));

            Marshal.StructureToPtr(ssid, ssidPtr, false);

            try
            {
                IntPtr bssListPtr;
                WlanInterop.ThrowIfError(WlanInterop.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr));

                try
                {
                    return(ConvertBssListPtr(bssListPtr));
                }
                finally
                {
                    WlanInterop.WlanFreeMemory(bssListPtr);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(ssidPtr);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Sets the profile.
        /// </summary>
        /// <param name="flags">The flags to set on the profile.</param>
        /// <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>
        /// <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>
        /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns>
        public WlanReasonCode SetProfile(WlanProfileFlags flags, string profileXml, bool overwrite)
        {
            WlanReasonCode reasonCode;

            WlanInterop.ThrowIfError(WlanInterop.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode));

            return(reasonCode);
        }
Beispiel #6
0
        /// <summary>
        /// Creates a new instance of a Native Wifi service client.
        /// Throws Win32 errors: ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, RPC_STATUS, ERROR_REMOTE_SESSION_LIMIT_EXCEEDED.
        /// </summary>
        public WlanClient()
        {
            int             errorCode = 0;
            OperatingSystem osInfo    = Environment.OSVersion;

            // this is winxp
            if (osInfo.Platform == PlatformID.Win32NT && osInfo.Version.Major == 5 && osInfo.Version.Minor != 0)
            {
                // wlanapi not supported in sp1 (or sp2 without fix)
                Console.WriteLine("xp sp " + osInfo.ServicePack);
                if (osInfo.ServicePack == "Service Pack 1")
                {
                    NoWifiAvailable = true;
                    return;
                }
                else if (osInfo.ServicePack == "Service Pack 2") // check if wlanapi is installed
                {
                    try
                    {
                        errorCode = WlanInterop.WlanOpenHandle(WlanInterop.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle);
                    }
                    catch
                    {
                        errorCode = NO_WIFI;
                    }
                }
            }
            else
            {
                errorCode = WlanInterop.WlanOpenHandle(WlanInterop.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle);
            }


            if (errorCode == NO_WIFI)
            {
                NoWifiAvailable = true;
                return;
            }
            // 1062 = no wifi
            // OK!
            WlanInterop.ThrowIfError(errorCode);

            try
            {
                // Interop callback
                wlanNotificationCallback = new WlanInterop.WlanNotificationCallbackDelegate(OnWlanNotification);

                WlanNotificationSource prevSrc;
                WlanInterop.ThrowIfError(WlanInterop.WlanRegisterNotification(clientHandle, WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
            }
            catch
            {
                WlanInterop.WlanCloseHandle(clientHandle, IntPtr.Zero);
                throw;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Gets a string that describes a specified reason code. NOTE: Not used!
        /// </summary>
        /// <param name="reasonCode">The reason code.</param>
        /// <returns>The string.</returns>
        internal static string GetStringForReasonCode(WlanReasonCode reasonCode)
        {
            StringBuilder sb = new StringBuilder(1024);             // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size

            if (WlanInterop.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero) != 0)
            {
                sb.Clear();                 // Not sure if we get junk in the stringbuilder buffer from WlanReasonCodeToString, clearing it to be sure.
                sb.Append("Failed to retrieve reason code, probably too small buffer.");
            }

            return(sb.ToString());
        }
Beispiel #8
0
        /// <summary>
        /// Creates a new instance of a Native Wifi service client.
        /// Throws Win32 errors: ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, RPC_STATUS, ERROR_REMOTE_SESSION_LIMIT_EXCEEDED.
        /// </summary>
        public WlanClient()
        {
            int             errorCode = 0;
            OperatingSystem osInfo    = Environment.OSVersion;

            bool isWinXP =
                osInfo.Platform == PlatformID.Win32NT &&
                osInfo.Version.Major == 5 &&
                osInfo.Version.Minor != 0;

            if (isWinXP && osInfo.ServicePack == "Service Pack 1")             // wlanapi not supported in sp1 (or sp2 without hotfix)
            {
                errorCode = NO_WIFI;
            }
            else
            {
                // Perform exception safe init
                // It can be SP2 without hotfix which would generate exception
                try
                {
                    errorCode = WlanInterop.WlanOpenHandle(WlanInterop.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle);
                }
                catch
                {
                    errorCode = NO_WIFI;
                }
            }

            if (errorCode != 0)
            {
                NoWifiAvailable = true;
                return;
            }

            // 1062 = no wifi
            // OK!
            // WlanInterop.ThrowIfError(errorCode);

            try
            {
                // Interop callback
                wlanNotificationCallback = new WlanInterop.WlanNotificationCallbackDelegate(OnWlanNotification);

                WlanNotificationSource prevSrc;
                WlanInterop.ThrowIfError(WlanInterop.WlanRegisterNotification(clientHandle, WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc));
            }
            catch
            {
                WlanInterop.WlanCloseHandle(clientHandle, IntPtr.Zero);
                throw;
            }
        }
Beispiel #9
0
        /// <summary>
        /// Sets a parameter of the interface whose data type is <see cref="int"/>.
        ///
        /// Possible Win32 errors:
        /// ERROR_ACCESS_DENIED: The caller does not have sufficient permissions to perform the requested operation.
        /// ERROR_GEN_FAILURE: The parameter specified by OpCode is not supported by the driver or NIC.
        /// ERROR_INVALID_HANDLE: The handle hClientHandle was not found in the handle table.
        /// ERROR_INVALID_PARAMETER: One parameter is likely NULL
        /// RPC_STATUS: Various return codes to indicate errors occurred when connecting.
        /// </summary>
        /// <param name="opCode">The opcode of the parameter.</param>
        /// <param name="value">The value to set.</param>
        private void SetInterfaceInt(WlanIntfOpcode opCode, int value)
        {
            IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int));

            Marshal.WriteInt32(valuePtr, value);

            try
            {
                WlanInterop.ThrowIfError(WlanInterop.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero));
            }
            finally
            {
                Marshal.FreeHGlobal(valuePtr);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Retrieves the basic service sets (BSS) list of all available networks.
        /// </summary>
        public WlanBssEntry[] GetNetworkBssList()
        {
            IntPtr bssListPtr;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr));

            try
            {
                return(ConvertBssListPtr(bssListPtr));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(bssListPtr);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Retrieves the list of available networks.
        /// </summary>
        /// <param name="flags">Controls the type of networks returned.</param>
        /// <returns>A list of the available networks.</returns>
        public WlanAvailableNetwork[] GetAvailableNetworkList(WlanGetAvailableNetworkFlags flags)
        {
            IntPtr availNetListPtr;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr));

            try
            {
                return(ConvertAvailableNetworkListPtr(availNetListPtr));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(availNetListPtr);
            }
        }
Beispiel #12
0
        /// <summary>
        /// Gets the profile's XML specification. Request Key unencrypted in plaintext.
        /// </summary>
        /// <param name="profileName">The name of the profile.</param>
        /// <returns>The XML document.</returns>
        public string GetProfileXmlUnencrypted(string profileName)
        {
            IntPtr           profileXmlPtr;
            WlanProfileFlags flags  = WlanProfileFlags.GetPlaintextKey;           // | WlanProfileFlags.User;
            WlanAccess       access = WlanAccess.ReadAccess;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, out access));
            try
            {
                return(Marshal.PtrToStringUni(profileXmlPtr));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(profileXmlPtr);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Gets a parameter of the interface whose data type is <see cref="int"/>.
        ///
        /// Possible Win32 errors:
        /// ERROR_ACCESS_DENIED: The caller does not have sufficient permissions to perform the requested operation.
        /// ERROR_INVALID PARAMETER: hClientHandle is NULL or invalid, pInterfaceGuid is NULL, pReserved is not NULL, ppData is NULL, or pdwDataSize is NULL.
        /// ERROR_INVALID_HANDLE: The handle hClientHandle was not found in the handle table.
        /// ERROR_INVALID_STATE: OpCode is set to wlan_intf_opcode_current_connection and the client is not currently connected to a network.
        /// ERROR_NOT_ENOUGH_MEMORY: Failed to allocate memory for the query results.
        /// RPC_STATUS: Various error codes.
        /// </summary>
        /// <param name="opCode">The opcode of the parameter.</param>
        /// <returns>The integer value.</returns>
        private int GetInterfaceInt(WlanIntfOpcode opCode)
        {
            IntPtr valuePtr;
            int    valueSize;
            WlanOpcodeValueType opcodeValueType;

            WlanInterop.ThrowIfError(WlanInterop.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));

            try
            {
                return(Marshal.ReadInt32(valuePtr));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(valuePtr);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Get Radio State
        /// </summary>
        /// <returns>Radio State</returns>
        internal WlanRadioState GetRadioState()
        {
            IntPtr valuePtr;
            int    valueSize;
            WlanOpcodeValueType opcodeValueType;

            WlanInterop.ThrowIfError(WlanInterop.WlanQueryInterface(_client.ClientHandle, _info.interfaceGuid, WlanIntfOpcode.RadioState, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));

            try
            {
                return((WlanRadioState)Marshal.PtrToStructure(valuePtr, typeof(WlanRadioState)));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(valuePtr);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Gets the profile's XML specification.
        /// </summary>
        /// <param name="profileName">The name of the profile.</param>
        /// <param name="isProtected">If True KeyMaterial Will show crypted(It can be use after windows 7)</param>
        /// <returns>The XML document.</returns>
        public string GetProfileXml(string profileName, bool isProtected)
        {
            IntPtr profileXmlPtr;
            //It Only Work After Windows 7 (GetPlaintextKey)
            WlanProfileFlags flags = isProtected ? WlanProfileFlags.AllUser : WlanProfileFlags.GetPlaintextKey;
            WlanAccess       access;

            WlanInterop.ThrowIfError(WlanInterop.WlanGetProfile(_client.ClientHandle, _info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, ref flags, out access));

            try
            {
                return(Marshal.PtrToStringUni(profileXmlPtr));
            }
            finally
            {
                WlanInterop.WlanFreeMemory(profileXmlPtr);
            }
        }
Beispiel #16
0
        public void GetNetwork()
        {
            WlanInterop.WlanGetAvailableNetworkList(handle, ref guid, 1, IntPtr.Zero, out IntPtr ppAvailableNetworkList);

            UInt32 dwNumberOfItems = (UInt32)Marshal.ReadInt32(ppAvailableNetworkList, 0);
            UInt32 dwIndex         = (UInt32)Marshal.ReadInt32(ppAvailableNetworkList, sizeof(UInt32));

            ppAvailableNetworkList += 2 * sizeof(UInt32);


            AvailableNetwork[] wlanInterface = new AvailableNetwork[dwNumberOfItems];

            Int32 sizeOfStruct = Marshal.SizeOf(typeof(AvailableNetwork));

            for (int i = 0; i < dwNumberOfItems; i++)
            {
                wlanInterface[i] = (AvailableNetwork)Marshal.PtrToStructure(ppAvailableNetworkList + sizeOfStruct * i, typeof(AvailableNetwork));
            }
        }
Beispiel #17
0
        //It Will Change throwiferror to this.
        private string GetErrorMessage(int errorCode)
        {
            int    FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
            int    FORMAT_MESSAGE_IGNORE_INSERTS  = 0x00000200;
            int    FORMAT_MESSAGE_FROM_SYSTEM     = 0x00001000;
            int    messageSize = 255;
            String lpMsgBuf    = "";
            int    dwFlags     = FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                 FORMAT_MESSAGE_FROM_SYSTEM |
                                 FORMAT_MESSAGE_IGNORE_INSERTS;
            IntPtr ptrlpSource  = new IntPtr();
            IntPtr prtArguments = new IntPtr();
            int    retVal       = WlanInterop.FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0,
                                                            ref lpMsgBuf, messageSize,
                                                            ref prtArguments);

            if (0 == retVal)
            {
                throw new Exception("Failed to format message for error code " +
                                    errorCode + ". ");
            }
            return(lpMsgBuf);
        }
Beispiel #18
0
 public void SetEAP(string profileName, string userXML)
 {
     WlanInterop.ThrowIfError(WlanInterop.WlanSetProfileEapXmlUserData(client.clientHandle, info.interfaceGuid, profileName, SetEapUserDataMode.None, userXML, IntPtr.Zero));
 }
Beispiel #19
0
 public void Open()
 {
     errorCode = WlanInterop.WlanOpenHandle(2u, IntPtr.Zero, out UInt32 pdwNegotiatedVersion, out handle);
 }
Beispiel #20
0
 public void Disconnect()
 {
     WlanInterop.ThrowIfError(WlanInterop.WlanDisconnect(client.clientHandle, info.interfaceGuid, IntPtr.Zero));
 }
Beispiel #21
0
 /// <summary>
 /// Connects to a network defined by a connection parameters structure.
 /// </summary>
 /// <param name="connectionParams">The connection paramters.</param>
 protected void Connect(WlanConnectionParameters connectionParams)
 {
     WlanInterop.ThrowIfError(WlanInterop.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero));
 }
Beispiel #22
0
 /// <summary>
 /// Requests a scan for available networks.
 /// </summary>
 /// <remarks>
 /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event.
 /// </remarks>
 public void Scan()
 {
     WlanInterop.ThrowIfError(WlanInterop.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero));
 }
Beispiel #23
0
 public void OnQuit()
 {
     WlanInterop.WlanCloseHandle(clientHandle, IntPtr.Zero);
     WlanInterop.UnloadImportedDll("wlanapi.dll");
 }
Beispiel #24
0
 /// <summary>
 /// Deletes a profile.
 /// </summary>
 /// <param name="profileName">
 /// 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 <c>-adhoc</c>.
 /// </param>
 public void DeleteProfile(string profileName)
 {
     WlanInterop.ThrowIfError(WlanInterop.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero));
 }