Repository navigation
Expand file tree
/
Copy pathPortProbe.cs
More file actions
59 lines (55 loc) · 2.4 KB
/
Copy pathPortProbe.cs
File metadata and controls
59 lines (55 loc) · 2.4 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
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace NETworkManager.Models.Network;
/// <summary>
/// Provides a shared, fully asynchronous TCP connect probe used by <see cref="IPScanner" /> and
/// <see cref="PortScanner" />.
/// </summary>
internal static class PortProbe
{
/// <summary>
/// Attempts a TCP connect to the given <paramref name="ipAddress" /> and <paramref name="port" /> and
/// classifies the result. Never throws for expected connect failures.
/// </summary>
/// <param name="ipAddress">IP address to connect to.</param>
/// <param name="port">Port to connect to.</param>
/// <param name="timeoutMs">Timeout in milliseconds after which the port is considered timed out.</param>
/// <param name="cancellationToken">Token to monitor for cancellation requests.</param>
/// <returns>The <see cref="PortState" /> of the probed port.</returns>
public static async Task<PortState> ProbeAsync(IPAddress ipAddress, int port, int timeoutMs,
CancellationToken cancellationToken)
{
using var tcpClient = new TcpClient(ipAddress.AddressFamily);
using var timeoutCts = new CancellationTokenSource(timeoutMs);
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
try
{
await tcpClient.ConnectAsync(ipAddress, port, linkedCts.Token).ConfigureAwait(false);
return tcpClient.Connected ? PortState.Open : PortState.Closed;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// linkedCts was canceled, but not by the caller -> our own timeout fired
return PortState.TimedOut;
}
catch (OperationCanceledException)
{
// Caller's token is why this was canceled -> propagate as a real cancellation
throw;
}
catch (Exception)
{
// Any other connect failure (refused, unreachable, etc.) -> always Closed, regardless
// of whether cancellation also happens to be in flight concurrently for an unrelated
// reason (that used to race against this classification via a token-state check here).
return PortState.Closed;
}
finally
{
tcpClient.Close();
}
}
}