wmash
wmash

Reputation: 4202

Check if connected via Ethernet C#

I've read a few sources on this. I followed this accepted answer and am using Managed WiFi API to get the SSID if I am connected via WiFi. Here is my code:

private void setSSID() {
    WlanClient wlan = new WlanClient();

    Collection<String> connectedSsids = new Collection<string>();

    foreach (WlanClient.WlanInterface wlanInterface in wlan.Interfaces) {
        Wlan.Dot11Ssid ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid;
        connectedSsids.Add(new String(Encoding.ASCII.GetChars(ssid.SSID, 0, (int)ssid.SSIDLength)));
    }
}

This will get the SSID perfectly if I am connected via WiFi but throws an exception if only connected via Ethernet. The ideal solution:

  1. Enter setSSID() (or something to similar effect)
  2. Check if connected via Ethernet
  3. If so, return null/0/undefined
  4. Else, return the SSID
    (I have already got a check in if it's even connected to the network or not)

I have looked all over the WMI and the NetworkInformation namespace but neither provide what I am looking for.
Looking in WlanApi.cs, the exception is thrown here:

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);
        }
    }
} 

Also looked at:

Upvotes: 2

Views: 1110

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

You can catch the exception (which you report as Win32Exception), and treat that as the "no WiFi is available" condition.

If you like, you can check the ErrorCode or HResult properties for the exception to make sure it's the error you were expecting in the case of the lack of WiFi, rather than some other more problematic exception. In the latter case, you would probably want to rethrow the exception (at least until you have decided on a good strategy for handling that type of error).

There is also the native wireless LAN API which you could use directly, handling the error codes/results from that instead of dealing with exceptions. But I think in your case, handling the exception that's thrown is simplest, since it otherwise is working just as you want.

Upvotes: 2

Related Questions