emoacht / ManagedNativeWifi

A managed implementation of Native Wifi API
MIT License
139 stars 41 forks source link

Establish a new connection #25

Closed hhgm closed 1 year ago

hhgm commented 2 years ago

Nice framework... but I am trying to establish a connection to an available network. I have connected manually, and made a snapshot of the XML. Then removed the connection.

I am able to find the network,

I pass in the SSID I want to connect to (yes, it is found..). I also pass the profileSecurity to use... but not really sure what to put there. From my XML I tried bot AES as well as WPA2PSK. But, SetProfile always returns false. And not sure how to extract an error message about what went wrong. That would be nice.

As the profile fails, the ConnectNetwork also fails, but that would be expected I think.

Any pointer would be nice. And a bit more documentation on these points would make the tool a lot better.

// get the network to connect to
var availableNetwork = NativeWifi.EnumerateAvailableNetworks()
    .FirstOrDefault(x => x.Ssid.ToString() == ssid);

if (availableNetwork is null)
    return;

var profile = NativeWifi.EnumerateProfiles().FirstOrDefault(x => x.Name == ssid);

if (profile is null)
{
    // build XML
    // Connects to a known network with WEP security
    string profileName = ssid; // this is also the SSID
    string mac = StringToHex(profileName);
    string profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns = \"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>true</protected><keyMaterial>... key removed for security...</keyMaterial></sharedKey></security></MSM><MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization><randomizationSeed>153878511</randomizationSeed></MacRandomization></WLANProfile>", ssid, mac);

    // create a profile
    var profileResult = NativeWifi.SetProfile(availableNetwork.Interface.Id, ProfileType.AllUser, profileXml, encryption, true);
}
else
{
    //todo: log here
}

var wasConnected = NativeWifi.ConnectNetwork(availableNetwork.Interface.Id, ssid, availableNetwork.BssType);
emoacht commented 1 year ago

If you wish to see the error reason, check pdwReasonCode.

https://github.com/emoacht/ManagedNativeWifi/blob/5628e53f9ad8e770e58e19edb73d7093b056af39/Source/ManagedNativeWifi/Win32/BaseMethod.cs#L324-L334