Repository navigation
Expand file tree
/
Copy pathWiFi.cs
More file actions
386 lines (339 loc) · 15.9 KB
/
Copy pathWiFi.cs
File metadata and controls
386 lines (339 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using NETworkManager.Models.Lookup;
namespace NETworkManager.Models.Network;
/// <summary>
/// Class with Wi-Fi related methods.
/// </summary>
public static class WiFi
{
private static readonly ILog Log = LogManager.GetLogger(typeof(WiFi));
/// <summary>
/// Get all Wi-Fi adapters async with additional information from <see cref="NetworkInterface" />.
/// </summary>
/// <returns>
/// <see cref="WiFiAdapterInfo" /> with <see cref="NetworkInterface" /> and <see cref="WiFiAdapter" /> as
/// <see cref="List{T}" />.
/// </returns>
public static async Task<List<WiFiAdapterInfo>> GetAdapterAsync()
{
List<WiFiAdapterInfo> wifiAdapterInfos = [];
var wifiAdapters = await WiFiAdapter.FindAllAdaptersAsync();
if (wifiAdapters.Count <= 0)
return wifiAdapterInfos;
var networkInterfaces = await NetworkInterface.GetNetworkInterfacesAsync();
foreach (var wiFiAdapter in wifiAdapters)
{
var wiFiAdapterId = wiFiAdapter.NetworkAdapter.NetworkAdapterId.ToString();
var networkInterface = networkInterfaces.FirstOrDefault(x => x.Id.TrimStart('{').TrimEnd('}')
.Equals(wiFiAdapterId, StringComparison.OrdinalIgnoreCase));
if (networkInterface != null)
wifiAdapterInfos.Add(new WiFiAdapterInfo
{
NetworkInterfaceInfo = networkInterface,
WiFiAdapter = wiFiAdapter
});
else
Log.Warn($"Could not find network interface for WiFi adapter with id: {wiFiAdapterId}");
}
return wifiAdapterInfos;
}
/// <summary>
/// Get all available Wi-Fi networks for an adapter with additional information's.
/// </summary>
/// <param name="adapter">WiFi adapter as <see cref="WiFiAdapter" />.</param>
/// <returns>A report as <see cref="WiFiNetworkScanInfo" /> including a list of <see cref="WiFiNetworkInfo" />.</returns>
public static async Task<WiFiNetworkScanInfo> GetNetworksAsync(WiFiAdapter adapter)
{
// Scan network adapter async
await adapter.ScanAsync();
// Try to get the current connected Wi-Fi network of this network adapter
var (_, bssid) = TryGetConnectedNetworkFromWiFiAdapter(adapter.NetworkAdapter.NetworkAdapterId.ToString());
var wifiNetworkInfos = new List<WiFiNetworkInfo>();
foreach (var availableNetwork in adapter.NetworkReport.AvailableNetworks)
{
var channelFrequencyInGigahertz = ConvertChannelFrequencyToGigahertz(availableNetwork.ChannelCenterFrequencyInKilohertz);
var wifiNetworkInfo = new WiFiNetworkInfo
{
AvailableNetwork = availableNetwork,
Radio = GetWiFiRadioFromChannelFrequency(channelFrequencyInGigahertz),
ChannelCenterFrequencyInGigahertz = channelFrequencyInGigahertz,
Channel = GetChannelFromChannelFrequency(channelFrequencyInGigahertz),
IsHidden = string.IsNullOrEmpty(availableNetwork.Ssid),
IsConnected = availableNetwork.Bssid.Equals(bssid, StringComparison.OrdinalIgnoreCase),
NetworkAuthenticationType = GetHumanReadableNetworkAuthenticationType(availableNetwork.SecuritySettings.NetworkAuthenticationType),
Vendor = (await OUILookup.LookupByMacAddressAsync(availableNetwork.Bssid)).FirstOrDefault()?.Vendor ?? "-/-",
PhyKind = GetHumanReadablePhyKind(availableNetwork.PhyKind)
};
wifiNetworkInfos.Add(wifiNetworkInfo);
}
return new WiFiNetworkScanInfo
{
NetworkAdapterId = adapter.NetworkAdapter.NetworkAdapterId,
WiFiNetworkInfos = wifiNetworkInfos,
Timestamp = adapter.NetworkReport.Timestamp.LocalDateTime
};
}
/// <summary>
/// Try to get the current connected Wi-Fi network (SSID and BSSID) of a network adapter from
/// netsh.exe.
/// Calling netsh.exe and parsing the output feels so dirty, but Microsoft's API returns only
/// the WLAN profile and the SSID of the connected network. The BSSID is needed to find a
/// specific access point among several.
/// </summary>
/// <param name="adapterId">GUID of the Wi-Fi network adapter.</param>
/// <returns>SSID and BSSID of the connected Wi-Fi network. Values are null if not detected.</returns>
// ReSharper disable once UnusedTupleComponentInReturnValue
private static (string SSID, string BSSID) TryGetConnectedNetworkFromWiFiAdapter(string adapterId)
{
string ssid = null;
string bssid = null;
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.AddScript("netsh wlan show interfaces");
var psOutputs = powerShell.Invoke();
/*
if (powerShell.Streams.Error.Count > 0) { // Handle error? }
if (powerShell.Streams.Warning.Count > 0) { // Handle warning? }
*/
/* Each object looks like this:
*
* Name : Wireless
* Description : Intel ...
* GUID : 90d8...
* SSID : Devices
* BSSID : 6a:d7:...
*/
var foundAdapter = false;
foreach (var outputItem in psOutputs)
{
// Find line with the network adapter id...
if (outputItem.ToString().Contains(adapterId, StringComparison.OrdinalIgnoreCase))
foundAdapter = true;
// ...and skip all lines until we found it.
if (!foundAdapter)
continue;
// Extract SSID from the line
if (outputItem.ToString().Contains(" SSID ", StringComparison.OrdinalIgnoreCase))
ssid = outputItem.ToString().Split(':')[1].Trim();
// Extract BSSID from the line
if (outputItem.ToString().Contains(" BSSID ", StringComparison.OrdinalIgnoreCase))
bssid = outputItem.ToString().Split(':', 2)[1].Trim();
// Break if we got the values, otherwise we might overwrite them
// with values from another adapter.
if (!string.IsNullOrEmpty(ssid) && !string.IsNullOrEmpty(bssid))
break;
}
}
return (ssid, bssid);
}
/// <summary>
/// Connect to a Wi-Fi network with Pre-shared key, EAP or no security.
/// </summary>
/// <param name="adapter">Wi-Fi adapter which should be used for the connection.</param>
/// <param name="network">Wi-Fi network to connect to.</param>
/// <param name="reconnectionKind">Reconnection type to automatically or manuel reconnect.</param>
/// <param name="credential">Credentials for EAP or PSK. Empty for open networks.</param>
/// <param name="ssid">SSID for hidden networks.</param>
/// <returns></returns>
public static async Task<WiFiConnectionStatus> ConnectAsync(WiFiAdapter adapter, WiFiAvailableNetwork network,
WiFiReconnectionKind reconnectionKind, PasswordCredential credential, string ssid = null)
{
WiFiConnectionResult connectionResult;
if (string.IsNullOrEmpty(ssid))
connectionResult = await adapter.ConnectAsync(network, reconnectionKind, credential);
else
connectionResult = await adapter.ConnectAsync(network, reconnectionKind, credential, ssid);
// Wrong password may cause connection to timeout.
// Disconnect any network from the adapter to return it to a non-busy state.
if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout)
Disconnect(adapter);
return connectionResult.ConnectionStatus;
}
/// <summary>
/// Connect to a Wi-Fi network with WPS push button.
/// </summary>
/// <param name="adapter">Wi-Fi adapter which should be used for the connection.</param>
/// <param name="network">Wi-Fi network to connect to.</param>
/// <param name="reconnectionKind">Reconnection type to automatically or manuel reconnect.</param>
/// <returns></returns>
public static async Task<WiFiConnectionStatus> ConnectWpsAsync(WiFiAdapter adapter, WiFiAvailableNetwork network,
WiFiReconnectionKind reconnectionKind)
{
var connectionResult = await adapter.ConnectAsync(network, reconnectionKind, null,
string.Empty, WiFiConnectionMethod.WpsPushButton);
// Wrong password may cause connection to timeout.
// Disconnect any network from the adapter to return it to a non-busy state.
if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Timeout)
Disconnect(adapter);
return connectionResult.ConnectionStatus;
}
/// <summary>
/// Disconnect the Wi-Fi adapter from the current Wi-Fi network.
/// </summary>
/// <param name="adapter">Wi-Fi adapter from which the Wi-Fi network should be disconnected.</param>
public static void Disconnect(WiFiAdapter adapter)
{
adapter.Disconnect();
}
/// <summary>
/// Get the connect mode of a Wi-Fi network like Open, Eap (WPA2-Enterprise)
/// or Psk (WPA2-Personal).
/// </summary>
/// <param name="network">Wi-Fi network as <see cref="WiFiAvailableNetwork" />.</param>
/// <returns>Connect mode as <see cref="WiFiConnectMode" />.</returns>
public static WiFiConnectMode GetConnectMode(WiFiAvailableNetwork network)
{
// Enterprise
if (network.SecuritySettings.NetworkAuthenticationType is NetworkAuthenticationType.Rsna or NetworkAuthenticationType.Wpa)
return WiFiConnectMode.Eap;
// Open
if (network.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 ||
network.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
return WiFiConnectMode.Open;
// Pre-Shared-Key
return WiFiConnectMode.Psk;
}
/// <summary>
/// Check if WPS is available for a Wi-Fi network.
/// </summary>
/// <param name="adapter">WiFi adapter as <see cref="WiFiAdapter" />.</param>
/// <param name="network">WiFi network as <see cref="WiFiAvailableNetwork" />.</param>
/// <returns>Ture if WPS is available.</returns>
public static async Task<bool> IsWpsAvailable(WiFiAdapter adapter, WiFiAvailableNetwork network)
{
var result = await adapter.GetWpsConfigurationAsync(network);
return result.SupportedWpsKinds.Contains(WiFiWpsKind.PushButton);
}
/// <summary>
/// Get the Wi-Fi channel from channel frequency.
/// </summary>
/// <param name="gigahertz">Input like 2.422 or 5.240.</param>
/// <returns>WiFi channel like 3 or 48.</returns>
public static int GetChannelFromChannelFrequency(double gigahertz)
{
return gigahertz switch
{
// 2.4 GHz
2.412 => 1,
2.417 => 2,
2.422 => 3,
2.427 => 4,
2.432 => 5,
2.437 => 6,
2.442 => 7,
2.447 => 8,
2.452 => 9,
2.457 => 10,
2.462 => 11,
2.467 => 12,
2.472 => 13,
2.484 => 14, // Most countries do not allow this channel
// 5 GHz
5.180 => 36, // UNII-1
5.200 => 40, // UNII-1
5.220 => 44, // UNII-1
5.240 => 48, // UNII-1
5.260 => 52, // UNII-2, DFS
5.280 => 56, // UNII-2, DFS
5.300 => 60, // UNII-2, DFS
5.320 => 64, // UNII-2, DFS
5.500 => 100, // UNII-2 Extended, DFS
5.520 => 104, // UNII-2 Extended, DFS
5.540 => 108, // UNII-2 Extended, DFS
5.560 => 112, // UNII-2 Extended, DFS
5.580 => 116, // UNII-2 Extended, DFS
5.600 => 120, // UNII-2 Extended, DFS
5.620 => 124, // UNII-2 Extended, DFS
5.640 => 128, // UNII-2 Extended, DFS
5.660 => 132, // UNII-2 Extended, DFS
5.680 => 136, // UNII-2 Extended, DFS
5.700 => 140, // UNII-2 Extended, DFS
5.720 => 144, // UNII-2 Extended, DFS
5.745 => 149, // UNII-3
5.765 => 153, // UNII-3
5.785 => 157, // UNII-3
5.805 => 161, // UNII-3
5.825 => 165, // UNII-3
_ => -1
};
}
/// <summary>
/// Convert the channel frequency to gigahertz.
/// </summary>
/// <param name="kilohertz">Frequency in kilohertz like 2422000 or 5240000.</param>
/// <returns>Frequency in gigahertz like 2.422 or 5.240.</returns>
public static double ConvertChannelFrequencyToGigahertz(int kilohertz)
{
return Convert.ToDouble(kilohertz) / 1000 / 1000;
}
/// <summary>
/// Get the Wi-Fi radio like 2.4 GHz, 5 GHz, etc. from the channel frequency.
/// </summary>
/// <param name="gigahertz">Frequency in gigahertz like 2.412 or 5.180.</param>
/// <returns>Radio like 2.4 GHz, 5 GHz, etc. as <see cref="WiFiRadio" />.</returns>
public static WiFiRadio GetWiFiRadioFromChannelFrequency(double gigahertz)
{
return gigahertz switch
{
>= 2.412 and <= 2.484 => WiFiRadio.GHz2dot4,
>= 5.180 and <= 5.825 => WiFiRadio.GHz5,
>= 5.925 and <= 7.125 => WiFiRadio.GHz6,
_ => WiFiRadio.Unknown
};
}
/// <summary>
/// Get the human-readable network authentication type.
/// </summary>
/// <param name="networkAuthenticationType">Wi-Fi network authentication type as <see cref="NetworkAuthenticationType" />.</param>
/// <returns>Human-readable authentication type as string like "Open" or "WPA2 Enterprise".</returns>
public static string GetHumanReadableNetworkAuthenticationType(NetworkAuthenticationType networkAuthenticationType)
{
return networkAuthenticationType switch
{
NetworkAuthenticationType.None => "-/-",
NetworkAuthenticationType.Unknown => "Unknown",
NetworkAuthenticationType.Open80211 => "Open",
NetworkAuthenticationType.SharedKey80211 => "WEP",
NetworkAuthenticationType.Wpa => "WPA Enterprise",
NetworkAuthenticationType.WpaPsk => "WPA PSK",
NetworkAuthenticationType.WpaNone => "WPA None",
NetworkAuthenticationType.Rsna => "WPA2 Enterprise",
NetworkAuthenticationType.RsnaPsk => "WPA2 Personal (PSK)",
NetworkAuthenticationType.Ihv => "IHV",
NetworkAuthenticationType.Wpa3Enterprise192Bits => "WPA3 Enterprise (192-bit)", // Same as Wpa3
NetworkAuthenticationType.Wpa3Sae => "WPA3 Personal (SAE)",
NetworkAuthenticationType.Owe => "OWE",
NetworkAuthenticationType.Wpa3Enterprise => "WPA3 Enterprise",
_ => "-/-"
};
}
/// <summary>
/// Get the human-readable network phy kind.
/// </summary>
/// <param name="phyKind">Wi-Fi network phy kind as <see cref="WiFiPhyKind" />.</param>
/// <returns>Human-readable phy kind as string like "802.11g" or "802.11ax".</returns>
public static string GetHumanReadablePhyKind(WiFiPhyKind phyKind)
{
return phyKind switch
{
WiFiPhyKind.Unknown => "Unknown",
WiFiPhyKind.Dsss or WiFiPhyKind.Fhss => "802.11",
WiFiPhyKind.Ofdm => "802.11a",
WiFiPhyKind.Hrdsss => "802.11b",
WiFiPhyKind.Erp => "802.11g",
WiFiPhyKind.HT => "802.11n",
WiFiPhyKind.Vht => "802.11ac",
WiFiPhyKind.Dmg => "802.11ad",
WiFiPhyKind.HE => "802.11ax",
WiFiPhyKind.Eht => "802.11be",
_ => "-/-"
};
}
}