-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectNet.cs
More file actions
86 lines (77 loc) · 3.42 KB
/
selectNet.cs
File metadata and controls
86 lines (77 loc) · 3.42 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
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace Vorfol.Common {
public class SelectedNet {
public UnicastIPAddressInformation ipInfo;
public PhysicalAddress mac;
}
public class SelectNetFromConsole {
public static async Task<SelectedNet> start() {
string choice = "";
Console.WriteLine("Select interface");
List<NetworkInterface> netCards = new List<NetworkInterface>();
foreach(var netCard in NetworkInterface.GetAllNetworkInterfaces()) {
if (netCard.OperationalStatus == OperationalStatus.Up) {
netCards.Add(netCard);
string mac = netCard.GetPhysicalAddress().ToString();
string ipAddr = "";
foreach(var card_addr in netCard.GetIPProperties().UnicastAddresses) {
if (card_addr.Address.AddressFamily == AddressFamily.InterNetwork) {
ipAddr = card_addr.Address.ToString();
break;
}
}
Console.WriteLine(netCards.Count + ": " +
netCard.Name + ", " +
netCard.Description +
", MAC: " + (String.IsNullOrEmpty(mac)?"none":mac) +
", IP: " + (String.IsNullOrEmpty(ipAddr)?"none":ipAddr));
if (string.IsNullOrEmpty(choice) && !string.IsNullOrEmpty(mac)) {
choice = netCards.Count.ToString();
}
}
}
if (netCards.Count == 0) {
Console.WriteLine("No Ethernet found");
return null;
}
Console.Write("[" + choice + "] (you have only 5 seconds to choose another interface) ");
CancellationTokenSource cancelReadConsole = new CancellationTokenSource();
var readConsoleTask = Task.Run(async () => {
do {
while (!Console.KeyAvailable) {
await Task.Delay(100);
}
var inner_choice = Console.ReadKey(true).KeyChar.ToString();
int i = -1;
if (int.TryParse(inner_choice, out i)) {
--i;
if (i >= 0 && i < netCards.Count) {
choice = inner_choice;
return;
}
}
Console.Beep(400, 300);
} while(true);
}, cancelReadConsole.Token);
var completedTask = await Task.WhenAny(Task.Delay(5000), readConsoleTask);
cancelReadConsole.Cancel();
Console.WriteLine(choice);
int cardIdx = int.Parse(choice) - 1;
foreach(var unicastAddrress in netCards[cardIdx].GetIPProperties().UnicastAddresses) {
if (unicastAddrress.Address.AddressFamily == AddressFamily.InterNetwork) {
// RETURN NOW
return new SelectedNet() {
ipInfo = unicastAddrress,
mac = netCards[cardIdx].GetPhysicalAddress()
};
}
}
return null;
}
}
}