forked from tmoonlight/NSmartProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkUtil.cs
More file actions
384 lines (348 loc) · 12.7 KB
/
NetworkUtil.cs
File metadata and controls
384 lines (348 loc) · 12.7 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
using NSmartProxy.Data;
using NSmartProxy.Infrastructure;
using NSmartProxy.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NSmartProxy
{
public static class NetworkUtil
{
private const string PortReleaseGuid = "23495C95-AEB6-41C6-B8AF-D03025EF0AE6";
private static HashSet<int> _usedPorts = new HashSet<int>();
public static bool ReleasePort(int port)
{
try
{
mutex.WaitOne();
_usedPorts.Remove(port);
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally { mutex.ReleaseMutex(); }
}
private static readonly Mutex mutex = new Lazy<Mutex>(() =>
new Mutex(false,
PortReleaseGuid)).Value;
/*string.Concat("./Global/", PortReleaseGuid)*/
/// <summary>
/// 查找一个端口
/// </summary>
/// <param name="startPort"></param>
/// <returns></returns>
public static int FindOneAvailableTCPPort(int startPort)
{
return NetworkUtil.FindAvailableTCPPorts(startPort, 1)[0];
}
/// <summary>
/// Check if startPort is available, incrementing and
/// checking again if it's in use until a free port is found
/// </summary>
/// <param name="startPort">The first port to check</param>
/// <returns>The first available port</returns>
public static int[] FindAvailableTCPPorts(int startPort, int PortCount)
{
int[] arrangedPorts = new int[PortCount];
int port = startPort;
bool isAvailable = true;
var mutex = new Mutex(false,
PortReleaseGuid);
mutex.WaitOne(); //全局锁
try
{
for (int i = 0; i < PortCount; i++)
{
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints =
ipGlobalProperties.GetActiveTcpListeners();
do
{
if (!isAvailable)
{
port++;
isAvailable = true;
}
if (_usedPorts.Contains(port))
{
isAvailable = false;
continue;
}
foreach (IPEndPoint endPoint in endPoints)
{
if (endPoint.Port != port) continue;
isAvailable = false;
break;
}
} while (!isAvailable && port < IPEndPoint.MaxPort);
if (!isAvailable)
throw new ApplicationException("Not able to find a free TCP port.");
arrangedPorts[i] = port;
_usedPorts.Add(port);
}
return arrangedPorts;
}
finally
{
mutex.ReleaseMutex();
}
}
/// <summary>
/// 找出正在被使用的端口
/// </summary>
/// <param name="startPort">The first port to check</param>
/// <returns>The first available port</returns>
public static List<int> FindUnAvailableTCPPorts(List<int> ports)
{
//bool isAvailable = true;
List<int> usedPortList = new List<int>(ports.Count);
mutex.WaitOne();
try
{
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints =
ipGlobalProperties.GetActiveTcpListeners();
for (int i = ports.Count - 1; i > -1; i--)
{
if (ports[i] > 65535 || ports[i] < 1|| _usedPorts.Contains(ports[i]))
{
usedPortList.Add(ports[i]);
ports.Remove(ports[i]);
}
}
foreach (IPEndPoint endPoint in endPoints)
{
var thisPort = endPoint.Port;
if (ports.Any(p => p == thisPort))
{
usedPortList.Add(thisPort);
}
}
return usedPortList.Distinct().ToList();
}
finally
{
mutex.ReleaseMutex();
}
}
/// <summary>
/// 找UDP空闲端口
/// </summary>
/// <param name="startPort">The first port to check</param>
/// <returns>The first available port</returns>
public static int FindNextAvailableUDPPort(int startPort)
{
int port = startPort;
bool isAvailable = true;
var mutex = new Mutex(false,
string.Concat("Global/", PortReleaseGuid));
mutex.WaitOne();
try
{
IPGlobalProperties ipGlobalProperties =
IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endPoints =
ipGlobalProperties.GetActiveUdpListeners();
do
{
if (!isAvailable)
{
port++;
isAvailable = true;
}
foreach (IPEndPoint endPoint in endPoints)
{
if (endPoint.Port != port)
continue;
isAvailable = false;
break;
}
} while (!isAvailable && port < IPEndPoint.MaxPort);
if (!isAvailable)
throw new ApplicationException("Not able to find a free TCP port.");
return port;
}
finally
{
mutex.ReleaseMutex();
}
}
public static async Task<TcpClient> ConnectAndSend(string addess, int port, Protocol protocol, byte[] data, bool isClose = false)
{
TcpClient configClient = new TcpClient();
bool isConnected = false;
for (int j = 0; j < 3; j++)
{
var delayDispose = Task.Delay(Global.DefaultConnectTimeout).ContinueWith(_ => configClient.Dispose());
var connectAsync = configClient.ConnectAsync(addess, port);
//超时则dispose掉
var completedTask = await Task.WhenAny(delayDispose, connectAsync);
if (!connectAsync.IsCompleted)
{
Console.WriteLine("ConnectAndSend连接超时,5秒后重试");
await Task.Delay(5000);
}
else
{
isConnected = true;
break;
}
}
if (!isConnected) { Console.WriteLine("重试次数达到限制。"); throw new Exception("重试次数达到限制。"); }
var configStream = configClient.GetStream();
await configStream.WriteAsync(new byte[] { (byte)protocol }, 0, 1);
await configStream.WriteAndFlushAsync(data, 0, data.Length);
//Console.Write(protocol.ToString() + " proceed.");
Console.Write("->");
if (isClose)
configClient.Close();
return configClient;
}
/// <summary>
///linux需要添加或修改以下值以手动实现keepalive
/// vim /etc/sysctl.conf
///net.ipv4.tcp_keepalive_time = 300
///net.ipv4.tcp_keepalive_intvl = 10
///net.ipv4.tcp_keepalive_probes = 10
/// sysctl -p+-
/// </summary>
/// <param name="tcpClient"></param>
/// <param name="ErrorMsg"></param>
public static void SetKeepAlive(this TcpClient tcpClient, out string ErrorMsg)
{
ErrorMsg = "";
// not all platforms support IOControl
//try
//{
// var keepAliveValues = new KeepAliveValues
// {
// OnOff = 1,
// KeepAliveTime = 300000, // 300 seconds in milliseconds
// KeepAliveInterval = 10000 // 10 seconds in milliseconds
// };
// socket.IOControl(IOControlCode.KeepAliveValues, keepAliveValues.ToBytes(), null);
//}
//catch (PlatformNotSupportedException)
//{
// // most platforms should support this call to SetSocketOption, but just in case call it in a try/catch also
// try
// {
// socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
// }
// catch (PlatformNotSupportedException)
// {
// // ignore PlatformNotSupportedException
// }
//}
//return socket;
try
{
tcpClient.Client.IOControl(IOControlCode.KeepAliveValues, GetKeepAlivePkg(1, 10000, 20000), null);
}
catch (PlatformNotSupportedException)
{
// most platforms should support this call to SetSocketOption, but just in case call it in a try/catch also
try
{
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
}
catch (PlatformNotSupportedException ex)
{
//平台不支持
ErrorMsg = ex.Message;
}
}
}
/// <summary>
/// 生成keepalive包用于Socket.IOControl
/// </summary>
/// <param name="onOff">是否開啟 Keep-Alive(開 1/ 關 0)</param>
/// <param name="keepAliveTime">當開啟keep-Alive後經過多久時間(ms)開啟偵測</param>
/// <param name="keepAliveInterval">多久偵測一次</param>
/// <returns></returns>
static byte[] GetKeepAlivePkg(int onOff, int keepAliveTime, int keepAliveInterval)
{
byte[] buffer = new byte[12];
BitConverter.GetBytes(onOff).CopyTo(buffer, 0);
BitConverter.GetBytes(keepAliveTime).CopyTo(buffer, 4);
BitConverter.GetBytes(keepAliveInterval).CopyTo(buffer, 8);
return buffer;
}
/// <summary>
/// 清空排除端口集合
/// </summary>
public static void ClearAllUsedPorts()
{
try
{
mutex.WaitOne();
_usedPorts = new HashSet<int>();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally { mutex.ReleaseMutex(); }
}
public static void ReAddUsedPorts(List<int> usedPorts)
{
ClearAllUsedPorts();
AddUsedPorts(usedPorts);
}
/// <summary>
/// 增加排除端口,这些端口永远不会被分配到
/// </summary>
/// <param name="usedPorts"></param>
public static void AddUsedPorts(List<int> usedPorts)
{
try
{
mutex.WaitOne();
foreach (var port in usedPorts)
{
if (!_usedPorts.Contains(port))
_usedPorts.Add(port);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally { mutex.ReleaseMutex(); }
}
/// <summary>
/// 删除排除端口
/// </summary>
/// <param name="usedPorts"></param>
public static void RemoveUsedPorts(List<int> usedPorts)
{
try
{
mutex.WaitOne();
foreach (var port in usedPorts)
{
usedPorts.Remove(port);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally { mutex.ReleaseMutex(); }
}
}
}