• Stars
    star
    139
  • Rank 262,954 (Top 6 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A managed implementation of Native Wifi API

Managed Native Wifi

ManagedNativeWifi is a managed implementation of Native Wifi API. It provides functionality to manage wireless networks, interfaces and profiles.

Requirements

This library works on Windows and compatible with:

.NET 6.0 .NET Standard 2.0 (including .NET Framework 4.6.1)

Download

NuGet: ManagedNativeWifi

Methods

Available methods including asynchronous ones based on TAP.

Method Description
EnumerateInterfaces Enumerates wireless interface information.
EnumerateInterfaceConnections Enumerates wireless interface and related connection information.
ScanNetworksAsync Asynchronously requests wireless interfaces to scan (rescan) wireless LANs.
EnumerateAvailableNetworkSsids Enumerates SSIDs of available wireless LANs.
EnumerateConnectedNetworkSsids Enumerates SSIDs of connected wireless LANs.
EnumerateAvailableNetworks Enumerates wireless LAN information on available networks.
EnumerateAvailableNetworkGroups Enumerates wireless LAN information on available networks and group of associated BSS networks.
EnumerateBssNetworks Enumerates wireless LAN information on BSS networks.
EnumerateProfileNames Enumerates wireless profile names in preference order.
EnumerateProfiles Enumerates wireless profile information in preference order.
EnumerateProfileRadios Enumerates wireless profile and related radio information in preference order.
SetProfile Sets (add or overwrite) the content of a specified wireless profile.
SetProfilePosition Sets the position of a specified wireless profile in preference order.
SetProfileEapXmlUserData Sets (add or overwirte) the EAP user credentials for a specified wireless profile.
RenameProfile Renames a specified wireless profile.
DeleteProfile Deletes a specified wireless profile.
ConnectNetwork Attempts to connect to the wireless LAN associated to a specified wireless profile.
ConnectNetworkAsync Asynchronously attempts to connect to the wireless LAN associated to a specified wireless profile.
DisconnectNetwork Disconnects from the wireless LAN associated to a specified wireless interface.
DisconnectNetworkAsync Asynchronously disconnects from the wireless LAN associated to a specified wireless interface.
GetInterfaceRadio Gets wireless interface radio information of a specified wireless interface.
TurnOnInterfaceRadio Turns on the radio of a specified wireless interface (software radio state only).
TurnOffInterfaceRadio Turns off the radio of a specified wireless interface (software radio state only).
IsInterfaceAutoConfig Checks if automatic configuration of a specified wireless interface is enabled.

Properties

Property Description
ThrowsOnAnyFailure Whether to throw an exception when any failure occurs

Usage

To check SSIDs of currently available wireless LANs, call EnumerateAvailableNetworkSsids method.

public static IEnumerable<string> EnumerateNetworkSsids()
{
    return NativeWifi.EnumerateAvailableNetworkSsids()
        .Select(x => x.ToString()); // UTF-8 string representation
}

In general, a SSID is represented by a UTF-8 string but it is not guaranteed. So if ToString method seems not to produce a valid value, try ToBytes method instead.

To connect to a wireless LAN, call ConnectNetworkAsync asynchronous method.

public static async Task<bool> ConnectAsync()
{
    var availableNetwork = NativeWifi.EnumerateAvailableNetworks()
        .Where(x => !string.IsNullOrWhiteSpace(x.ProfileName))
        .OrderByDescending(x => x.SignalQuality)
        .FirstOrDefault();

    if (availableNetwork is null)
        return false;

    return await NativeWifi.ConnectNetworkAsync(
        interfaceId: availableNetwork.Interface.Id,
        profileName: availableNetwork.ProfileName,
        bssType: availableNetwork.BssType,
        timeout: TimeSpan.FromSeconds(10));
}

This method returns true if successfully connected to the wireless LAN in contrast to its synchronous sibling, ConnectNetwork method, returns true if the request for the connection succeeds and doesn't indicate the result.

To refresh currently available wireless LANs, call ScanNetworksAsync method.

public static Task RefreshAsync()
{
    return NativeWifi.ScanNetworksAsync(timeout: TimeSpan.FromSeconds(10));
}

This method requests wireless interfaces to scan wireless LANs in parallel. It takes no more than 4 seconds.

To delete an existing wireless profile, use DeleteProfile method. Please note that a profile name is case-sensitive.

public static bool DeleteProfile(string profileName)
{
    var targetProfile = NativeWifi.EnumerateProfiles()
        .Where(x => profileName.Equals(x.Name, StringComparison.Ordinal))
        .FirstOrDefault();

    if (targetProfile is null)
        return false;

    return NativeWifi.DeleteProfile(
        interfaceId: targetProfile.Interface.Id,
        profileName: profileName);
}

To check wireless LAN channels that are already used by surrounding access points, call EnumerateBssNetworks method and filter the results by signal strength.

public static IEnumerable<int> EnumerateNetworkChannels(int signalStrengthThreshold)
{
    return NativeWifi.EnumerateBssNetworks()
        .Where(x => x.SignalStrength > signalStrengthThreshold)
        .Select(x => x.Channel);
}

To turn on the radio of a wireless interface, check the current radio state by GetInterfaceRadio method and then call TurnOnInterfaceRadio method.

public static async Task<bool> TurnOnAsync()
{
    var targetInterface = NativeWifi.EnumerateInterfaces()
        .FirstOrDefault(x =>
        {
            var radioSet = NativeWifi.GetInterfaceRadio(x.Id)?.RadioSets.FirstOrDefault();
            if (radioSet is null)
                return false;

            if (!radioSet.HardwareOn.GetValueOrDefault()) // Hardware radio state is off.
                return false;

            return (radioSet.SoftwareOn == false); // Software radio state is off.
        });

    if (targetInterface is null)
        return false;

    try
    {
        return await Task.Run(() => NativeWifi.TurnOnInterfaceRadio(targetInterface.Id));
    }
    catch (UnauthorizedAccessException)
    {
        return false;
    }
}

Please note that this method can only change software radio state and if hardware radio state is off (like hardware Wi-Fi switch is at off position), the radio cannot be turned on programatically.

Note

  • Creating a wireless profile from scratch is not covered in this library. It is because 1) Native WiFi does not include such functionality, 2) it requires careful consideration on wi-fi technology in use, 3) it involves sensitive security information. Thus, it is left to each user.

History

Ver 2.5 2023-1-9

  • Add: Setting property to throw an exception when any failure occurs; ThrowsOnAnyFailure

Ver 2.4 2022-11-24

  • Add: Special event args for AvailabilityChanged, InterfaceChanged, ConnectionChanged, ProfileChanged events
  • Breaking change: .NET 5.0 is no longer supported

Ver 2.3 2022-8-1

  • Add: PHY types (802.11ad, ax, be)
  • Add: PHY type in profile and related radio information

Ver 2.2 2022-7-25

  • Add: Method to set the EAP user credentials
  • Add: PHY type in BSS network
  • Breaking change: .NET Framework 4.6 or older is no longer supported

Ver 2.1 2021-3-30

  • Fix: GetInterfaceRadio is enabled to handle invalid capabilities information

Ver 2.0 2021-2-4

  • Add: Support for .NET 5.0 and .NET Standard 2.0

Ver 1.8 2020-12-20

  • Breaking change: GetInterfaceAutoConfig is renamed to IsInterfaceAutoConfig

Ver 1.7 2020-9-29

  • Add: WPA3 in authentication method and algorithm

Ver 1.6 2020-8-4

  • Add: Functionality to connect specific access point when connecting network

Ver 1.5 2019-12-1

  • Add: Information obtained by EnumerateAvailableNetworks and EnumerateAvailableNetworkGroups include authentication/cipher algorithms

Ver 1.4 2018-9-2

  • Add: Methods to provide additional information; EnumerateInterfaceConnections, EnumerateAvailableNetworkGroups, EnumerateProfileRadios
  • Breaking change: Radio information related to wireless profiles can be obtained by EnumerateProfileRadios instead of EnumerateProfiles

Ver 1.0 2015-1-30

  • Initial commit

License

  • MIT License

More Repositories

1

Monitorian

A Windows desktop tool to adjust the brightness of multiple monitors with ease
C#
3,278
star
2

Wifinian

A Windows desktop tool to enable user to actively control Wi-Fi connections
C#
241
star
3

DesktopToast

A library for toast notifications from desktop app
C#
117
star
4

HelloSwitcher

A Windows desktop tool to help switching cameras for Windows Hello
C#
37
star
5

RawInput.Touchpad

Sample to capture inputs from Precision Touchpad by Raw Input API
C#
35
star
6

SnowyImageCopy

A Windows desktop app to copy images from FlashAir by a wireless connection
C#
32
star
7

WpfMonitorAware

A library for Per-Monitor DPI aware and color profile aware Window
C#
32
star
8

HashPad

A simple tool to compute and compare hash value including from Explorer's context menu
C#
26
star
9

CortanaSwitcher

Enable/Disable Cortana in Windows 10 Anniversay Update
C#
14
star
10

ExifTimeShift

A simple tool to shift date/time of JPG files by directly changing Exif date fields while leaving other data intact
C#
14
star
11

WindowCornerTest

Rounded corners of window on Windows 11 applicable to WPF.
C#
9
star
12

DiskGazer

A high-definition disk measuring tool which can measure the transfer rates of a physical disk in a small unit and at any location in the disk
C#
8
star
13

WpfControlCollection

A collection of WPF controls such as ProgressBar.
C#
6
star
14

TrimCopy

A Visual Studio extension to copy code block trimming leading white spaces while keeping indentation structure
C#
4
star
15

DeviceDetect

Sample Windows service to detect device events
C#
3
star
16

BatteryProbe

A Windows desktop app to probe battery information
C#
3
star
17

WpfBuiltinDpiTest

Test WPF Built-in scaling for Per-Monitor DPI.
C#
3
star
18

WinFormsControlCollection

A collection of WinForms controls such as ProgressBar.
C#
2
star
19

PowerMapView

C#
2
star
20

OsVersionDetect

Sample methods to detect Windows OS versions
C#
2
star
21

StripeMaker

A design tool to create the tile visuals for striped background
C#
2
star
22

PowerMonitor

A library to check electric power data of Japanese electric power companies
Visual Basic .NET
2
star
23

FontAlignment

A set of tools for adjusting the vertical center of text taking font metric into account
C#
1
star
24

SdrTest

Test SDR.
C#
1
star
25

SynapseBane

Stop Razor Synapse 3 from automatically creating c:\temp\ folder by changing NLog config files.
C#
1
star
26

WindowsRuntimeSettings

A library for Windows Runtime app to save/load settings of various types with encryption if necessary
C#
1
star
27

LargeFileProxy

An attempt to make a proxy for a large text file delimited by line breaks.
C#
1
star
28

StringReaderCatalog

A catalog of methods to read string by C#, especially focusing on handling of Unicode BOM
C#
1
star
29

WpfColorManagement

A sample attached property of color profile for color management
C#
1
star
30

IlluminoChecker

Visualize ambient light sensor output and corresponding screen brightness adjusted by adaptive brightness.
C#
1
star