C# sample: quickly finding the name of the WiFi network you are connected to

Posted: (EET/GMT+2)

 

Today's post is a simple piece of C# code that you can use to quickly find the name (SSID) of the wireless WLAN network (WiFi) you are connected to. In Windows Vista and onwards (Windows 7 and 8 included), there's a nice native API called the "Native WiFi", which is aimed at C and C++ Win32 developers. However, there's a nice managed .NET wrapper built around this API, called the "Managed Wifi API", which is available as an open-source library at CodePlex.

The Managed Wifi API is probably the simplest way to find out information about your WiFi connections and available networks. Of course, you could implement the P/Invoke calls directly yourself, but getting all the variable-sized enums correctly defined can get tricky. Thus, the managed library saves you plenty of time.

To get this library working, you can either download the similarly names NuGet package, or just download two source code files from CodePlex: Interop.cs and WlanApi.cs.

Once you have these files in your project, you can proceed by creating an instance of the WlanClient class (in the NativeWifi namespace), and then call its methods and access its properties. The API also allows you to read the RSSI values of the networks (BSSs) available.

To get the name of the WiFi network you are currently connected to (if any), use the following code:

using NativeWifi;
...

WlanClient client = new WlanClient();
WlanClient.WlanInterface intf = client.Interfaces[0];
if (intf.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)
{
    string ssid = intf.CurrentConnection.profileName;
    MessageBox.Show("You are connected to WiFi network named " + ssid + ". " +
        "The signal strength is currently " + intf.RSSI + " dBm.");
}
else
{
    MessageBox.Show("The interface " + intf.InterfaceDescription +
        " is not currently connected to any network.");
}

The above code takes the first available physical WiFi interface on the computer, and checks to see if it is connected. If it is, the SSID (network name) is shown along with the RSSI signal strength in dBm.

Here's another example. To list all the available WiFi networks within range, you can use the following code:

using NativeWifi;
...

WlanClient client = new WlanClient();
WlanClient.WlanInterface intf = client.Interfaces[0];

Wlan.WlanBssEntry[] bss = intf.GetNetworkBssList();
foreach (Wlan.WlanBssEntry entry in bss)
{
    string ssid = ConvertSSIDBytesToString(entry.dot11Ssid);
    MessageBox.Show("Available WiFi network found: " + ssid + ". "+
        "The signal strength is currently " + entry.rssi + " dBm.");
}

Happy hacking!