|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.Linq; |
| 4 | +using System.Net; |
4 | 5 | using System.Net.Sockets; |
5 | 6 | using System.Text; |
6 | 7 | using System.Threading; |
7 | 8 | using System.Threading.Tasks; |
8 | 9 | using Shawn.Utils; |
| 10 | +using System.Net.NetworkInformation; |
9 | 11 |
|
10 | 12 | namespace _1RM.Utils |
11 | 13 | { |
12 | 14 | public static class TcpHelper |
13 | 15 | { |
| 16 | + public static (bool, IPAddress?) IsIPv6(string address) |
| 17 | + { |
| 18 | + if (IPAddress.TryParse(address, out var ipAddress)) |
| 19 | + { |
| 20 | + return (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6, ipAddress); |
| 21 | + } |
| 22 | + return (false, null); |
| 23 | + } |
| 24 | + |
14 | 25 | /// <summary> |
15 | 26 | /// return true if connected, false if not connected, null if timeout or cancelled. |
16 | 27 | /// </summary> |
17 | 28 | public static async Task<bool?> TestConnectionAsync(string address, int port, CancellationToken? cancellationToken = null, int timeOutMillisecond = 0) |
18 | 29 | { |
19 | | - using var client = new TcpClient(); |
| 30 | + var (isIPv6, iPv6) = IsIPv6(address); |
| 31 | + using var client = isIPv6 ? new TcpClient(iPv6!.AddressFamily) : new TcpClient(); |
20 | 32 | try |
21 | 33 | { |
22 | 34 | var cts = new CancellationTokenSource(); |
23 | 35 | cancellationToken ??= cts.Token; |
24 | 36 | #if NETCOREAPP |
25 | 37 | var connectTask = client.ConnectAsync(address, port, (CancellationToken)cancellationToken).AsTask(); |
26 | 38 | #else |
27 | | - var connectTask = client.ConnectAsync(address, port); |
| 39 | + var connectTask = isIPv6 ? client.ConnectAsync(iPv6, port) : client.ConnectAsync(address, port); |
28 | 40 | #endif |
29 | 41 | if (timeOutMillisecond <= 0) |
30 | 42 | timeOutMillisecond = 30 * 1000; |
|
0 commit comments