-
Notifications
You must be signed in to change notification settings - Fork 803
Expand file tree
/
Copy pathNetworkInterface.cs
More file actions
354 lines (299 loc) · 13.6 KB
/
NetworkInterface.cs
File metadata and controls
354 lines (299 loc) · 13.6 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.Win32;
using NETworkManager.Utilities;
namespace NETworkManager.Models.Network;
public sealed class NetworkInterface
{
#region Events
public event EventHandler UserHasCanceled;
private void OnUserHasCanceled()
{
UserHasCanceled?.Invoke(this, EventArgs.Empty);
}
#endregion
#region Methods
public static Task<List<NetworkInterfaceInfo>> GetNetworkInterfacesAsync()
{
return Task.Run(GetNetworkInterfaces);
}
public static List<NetworkInterfaceInfo> GetNetworkInterfaces()
{
List<NetworkInterfaceInfo> listNetworkInterfaceInfo = new();
foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
// NetworkInterfaceType 53 is proprietary virtual/internal interface
// https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types
if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet &&
networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
(int)networkInterface.NetworkInterfaceType != 53)
continue;
var listIPv4Address = new List<Tuple<IPAddress, IPAddress>>();
var listIPv6AddressLinkLocal = new List<IPAddress>();
var listIPv6Address = new List<IPAddress>();
var dhcpLeaseObtained = new DateTime();
var dhcpLeaseExpires = new DateTime();
var ipProperties = networkInterface.GetIPProperties();
foreach (var unicastIPAddrInfo in ipProperties.UnicastAddresses)
{
switch (unicastIPAddrInfo.Address.AddressFamily)
{
case AddressFamily.InterNetwork:
listIPv4Address.Add(new Tuple<IPAddress, IPAddress>(unicastIPAddrInfo.Address,
unicastIPAddrInfo.IPv4Mask));
dhcpLeaseExpires =
(DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressPreferredLifetime))
.ToLocalTime();
dhcpLeaseObtained =
(DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressValidLifetime) -
TimeSpan.FromSeconds(unicastIPAddrInfo.DhcpLeaseLifetime)).ToLocalTime();
break;
case AddressFamily.InterNetworkV6 when unicastIPAddrInfo.Address.IsIPv6LinkLocal:
listIPv6AddressLinkLocal.Add(unicastIPAddrInfo.Address);
break;
case AddressFamily.InterNetworkV6:
listIPv6Address.Add(unicastIPAddrInfo.Address);
break;
}
}
var listIPv4Gateway = new List<IPAddress>();
var listIPv6Gateway = new List<IPAddress>();
foreach (var gatewayIPAddrInfo in ipProperties.GatewayAddresses)
{
switch (gatewayIPAddrInfo.Address.AddressFamily)
{
case AddressFamily.InterNetwork:
listIPv4Gateway.Add(gatewayIPAddrInfo.Address);
break;
case AddressFamily.InterNetworkV6:
listIPv6Gateway.Add(gatewayIPAddrInfo.Address);
break;
}
}
// Check if autoconfiguration for DNS is enabled (only via registry key)
var nameServerKey =
Registry.LocalMachine.OpenSubKey(
$@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{networkInterface.Id}");
var dnsAutoconfigurationEnabled = nameServerKey?.GetValue("NameServer") != null &&
string.IsNullOrEmpty(nameServerKey.GetValue("NameServer")?.ToString());
// Check if IPv4 protocol is available
var ipv4ProtocolAvailable = true;
IPv4InterfaceProperties ipv4Properties = null;
try
{
ipv4Properties = ipProperties.GetIPv4Properties();
}
catch (NetworkInformationException)
{
ipv4ProtocolAvailable = false;
}
// Check if IPv6 protocol is available
var ipv6ProtocolAvailable = true;
try
{
ipProperties.GetIPv6Properties();
}
catch (NetworkInformationException)
{
ipv6ProtocolAvailable = false;
}
listNetworkInterfaceInfo.Add(new NetworkInterfaceInfo
{
Id = networkInterface.Id,
Name = networkInterface.Name,
Description = networkInterface.Description,
Type = networkInterface.NetworkInterfaceType.ToString(),
PhysicalAddress = networkInterface.GetPhysicalAddress(),
Status = networkInterface.OperationalStatus,
IsOperational = networkInterface.OperationalStatus == OperationalStatus.Up,
Speed = networkInterface.Speed,
IPv4ProtocolAvailable = ipv4ProtocolAvailable,
IPv4Address = listIPv4Address.ToArray(),
IPv4Gateway = listIPv4Gateway.ToArray(),
DhcpEnabled = ipv4Properties is { IsDhcpEnabled: true },
DhcpServer = ipProperties.DhcpServerAddresses.Where(dhcpServerIPAddress =>
dhcpServerIPAddress.AddressFamily == AddressFamily.InterNetwork).ToArray(),
DhcpLeaseObtained = dhcpLeaseObtained,
DhcpLeaseExpires = dhcpLeaseExpires,
IPv6ProtocolAvailable = ipv6ProtocolAvailable,
IPv6AddressLinkLocal = listIPv6AddressLinkLocal.ToArray(),
IPv6Address = listIPv6Address.ToArray(),
IPv6Gateway = listIPv6Gateway.ToArray(),
DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled,
DNSSuffix = ipProperties.DnsSuffix,
DNSServer = ipProperties.DnsAddresses.ToArray()
});
}
return listNetworkInterfaceInfo;
}
public static Task<IPAddress> DetectLocalIPAddressBasedOnRoutingAsync(IPAddress remoteIPAddress)
{
return Task.Run(() => DetectLocalIPAddressBasedOnRouting(remoteIPAddress));
}
private static IPAddress DetectLocalIPAddressBasedOnRouting(IPAddress remoteIPAddress)
{
var isIPv4 = remoteIPAddress.AddressFamily == AddressFamily.InterNetwork;
using var socket = new Socket(isIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
SocketType.Dgram, ProtocolType.Udp);
// return null on error...
try
{
socket.Bind(new IPEndPoint(isIPv4 ? IPAddress.Any : IPAddress.IPv6Any, 0));
socket.Connect(new IPEndPoint(remoteIPAddress, 0));
if (socket.LocalEndPoint is IPEndPoint ipAddress)
return ipAddress.Address;
}
catch (SocketException)
{
}
return null;
}
public static Task<IPAddress> DetectGatewayBasedOnLocalIPAddressAsync(IPAddress localIPAddress)
{
return Task.Run(() => DetectGatewayBasedOnLocalIPAddress(localIPAddress));
}
private static IPAddress DetectGatewayBasedOnLocalIPAddress(IPAddress localIPAddress)
{
foreach (var networkInterface in GetNetworkInterfaces())
if (localIPAddress.AddressFamily == AddressFamily.InterNetwork)
{
if (networkInterface.IPv4Address.Any(x => x.Item1.Equals(localIPAddress)))
return networkInterface.IPv4Gateway.FirstOrDefault();
}
else if (localIPAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
if (networkInterface.IPv6Address.Contains(localIPAddress))
return networkInterface.IPv6Gateway.FirstOrDefault();
}
else
{
throw new Exception("IPv4 or IPv6 address is required to detect the gateway.");
}
return null;
}
public Task ConfigureNetworkInterfaceAsync(NetworkInterfaceConfig config)
{
return Task.Run(() => ConfigureNetworkInterface(config));
}
private void ConfigureNetworkInterface(NetworkInterfaceConfig config)
{
// IP
var command = $"netsh interface ipv4 set address name='{config.Name}'";
command += config.EnableStaticIPAddress
? $" source=static address={config.IPAddress} mask={config.Subnetmask} gateway={config.Gateway};"
: " source=dhcp;";
// DNS
command += $"netsh interface ipv4 set DNSservers name='{config.Name}'";
command += config.EnableStaticDNS
? $" source=static address={config.PrimaryDNSServer} register=primary validate=no;"
: " source=dhcp;";
command += config.EnableStaticDNS && !string.IsNullOrEmpty(config.SecondaryDNSServer)
? $"netsh interface ipv4 add DNSservers name='{config.Name}' address={config.SecondaryDNSServer} index=2 validate=no;"
: "";
try
{
PowerShellHelper.ExecuteCommand(command, true);
}
catch (Win32Exception win32Ex)
{
switch (win32Ex.NativeErrorCode)
{
case 1223:
OnUserHasCanceled();
break;
default:
throw;
}
}
}
/// <summary>
/// Flush the DNS cache asynchronously.
/// </summary>
/// <returns>Running task.</returns>
public static Task FlushDnsAsync()
{
return Task.Run(FlushDns);
}
/// <summary>
/// Flush the DNS cache.
/// </summary>
private static void FlushDns()
{
const string command = "ipconfig /flushdns;";
PowerShellHelper.ExecuteCommand(command);
}
/// <summary>
/// Release or renew the IP address of the specified network adapter asynchronously.
/// </summary>
/// <param name="mode">ipconfig.exe modes which are used like /release(6) or /renew(6)</param>
/// <param name="adapterName">Name of the ethernet adapter.</param>
/// <returns>Running task.</returns>
public static Task ReleaseRenewAsync(IPConfigReleaseRenewMode mode, string adapterName)
{
return Task.Run(() => ReleaseRenew(mode, adapterName));
}
/// <summary>
/// Release or renew the IP address of the specified network adapter.
/// </summary>
/// <param name="mode">ipconfig.exe modes which are used like /release(6) or /renew(6)</param>
/// <param name="adapterName">Name of the ethernet adapter.</param>
private static void ReleaseRenew(IPConfigReleaseRenewMode mode, string adapterName)
{
var command = string.Empty;
if (mode is IPConfigReleaseRenewMode.ReleaseRenew or IPConfigReleaseRenewMode.Release)
command += $"ipconfig /release '{adapterName}';";
if (mode is IPConfigReleaseRenewMode.ReleaseRenew or IPConfigReleaseRenewMode.Renew)
command += $"ipconfig /renew '{adapterName}';";
if (mode is IPConfigReleaseRenewMode.ReleaseRenew6 or IPConfigReleaseRenewMode.Release6)
command += $"ipconfig /release6 '{adapterName}';";
if (mode is IPConfigReleaseRenewMode.ReleaseRenew6 or IPConfigReleaseRenewMode.Renew6)
command += $"ipconfig /renew6 '{adapterName}';";
PowerShellHelper.ExecuteCommand(command);
}
/// <summary>
/// Add an IP address to a network interface asynchronously.
/// </summary>
/// <param name="config">Ethernet adapter name, IP address and subnetmask.</param>
/// <returns>Running task.</returns>
public static Task AddIPAddressToNetworkInterfaceAsync(NetworkInterfaceConfig config)
{
return Task.Run(() => AddIPAddressToNetworkInterface(config));
}
/// <summary>
/// Add an IP address to a network interface.
/// </summary>
/// <param name="config">Ethernet adapter name, IP address and subnetmask.</param>
private static void AddIPAddressToNetworkInterface(NetworkInterfaceConfig config)
{
var command = string.Empty;
if (config.EnableDhcpStaticIpCoexistence)
command += $"netsh interface ipv4 set interface interface='{config.Name}' dhcpstaticipcoexistence=enabled;";
command += $"netsh interface ipv4 add address '{config.Name}' {config.IPAddress} {config.Subnetmask};";
PowerShellHelper.ExecuteCommand(command, true);
}
/// <summary>
/// Remove an IP address from a network interface asynchronously.
/// </summary>
/// <param name="config">Ethernet adapter name, IP address</param>
/// <returns>Running task.</returns>
public static Task RemoveIPAddressFromNetworkInterfaceAsync(NetworkInterfaceConfig config)
{
return Task.Run(() => RemoveIPAddressFromNetworkInterface(config));
}
/// <summary>
/// Remove an IP address from a network interface.
/// </summary>
/// <param name="config">Ethernet adapter name, IP address</param>
private static void RemoveIPAddressFromNetworkInterface(NetworkInterfaceConfig config)
{
var command = $"netsh interface ipv4 delete address '{config.Name}' {config.IPAddress};";
PowerShellHelper.ExecuteCommand(command, true);
}
#endregion
}