forked from ElectronNET/Electron.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPortHelper.cs
More file actions
90 lines (77 loc) · 2.39 KB
/
PortHelper.cs
File metadata and controls
90 lines (77 loc) · 2.39 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
namespace ElectronNET.Runtime.Helpers
{
using System.Linq;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
internal static class PortHelper
{
public static int GetFreePort(int? defaultPost)
{
var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners().Select(e => e.Port).ToList();
var localAddresses = GetLocalAddresses();
int port = defaultPost ?? 8000;
while (true)
{
if (!listeners.Contains(port) && TryBindPort(port, localAddresses))
{
return port;
}
port += 2;
}
}
private static HashSet<IPAddress> GetLocalAddresses()
{
var addresses = new HashSet<IPAddress>
{
IPAddress.Any,
IPAddress.IPv6Any,
IPAddress.Loopback,
IPAddress.IPv6Loopback
};
try
{
var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var networkInterface in networkInterfaces)
{
if (networkInterface.OperationalStatus != OperationalStatus.Up)
{
continue;
}
var ipProperties = networkInterface.GetIPProperties();
foreach (var unicastAddress in ipProperties.UnicastAddresses)
{
addresses.Add(unicastAddress.Address);
}
}
}
catch
{
// ignored
}
return addresses;
}
private static bool TryBindPort(int port, HashSet<IPAddress> addresses)
{
TcpListener listener = null;
foreach (var address in addresses)
{
try
{
listener = new TcpListener(address, port);
listener.Start();
}
catch
{
return false;
}
finally
{
listener?.Stop();
}
}
return true;
}
}
}