-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathRouteTableManager.cs
517 lines (472 loc) · 19.2 KB
/
RouteTableManager.cs
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
namespace SupersocksR.Net.Routing
{
using System;
using System.Net;
using System.Runtime.InteropServices;
public static class RouteTableManager
{
public enum MIB_IPFORWARD_TYPE : uint
{
/// <summary>
/// Some other type not specified in RFC 1354.
/// </summary>
MIB_IPROUTE_TYPE_OTHER = 1,
/// <summary>
/// An invalid route. This value can result from a route added by an ICMP redirect.
/// </summary>
MIB_IPROUTE_TYPE_INVALID = 2,
/// <summary>
/// A local route where the next hop is the final destination (a local interface).
/// </summary>
MIB_IPROUTE_TYPE_DIRECT = 3,
/// <summary>
/// The remote route where the next hop is not the final destination (a remote destination).
/// </summary>
MIB_IPROUTE_TYPE_INDIRECT = 4
}
public enum MIB_IPPROTO : uint
{
/// <summary>
/// Some other protocol not specified in RFC 1354.
/// </summary>
MIB_IPPROTO_OTHER = 1,
/// <summary>
/// A local interface.
/// </summary>
MIB_IPPROTO_LOCAL = 2,
/// <summary>
/// A static route.
/// This value is used to identify route information for IP routing
/// set through network management such as the Dynamic Host Configuration
/// Protocol (DCHP), the Simple Network Management Protocol (SNMP),
/// or by calls to the CreateIpForwardEntry, DeleteIpForwardEntry,
/// or SetIpForwardEntry functions.
/// </summary>
MIB_IPPROTO_NETMGMT = 3,
/// <summary>
/// The result of ICMP redirect.
/// </summary>
MIB_IPPROTO_ICMP = 4,
/// <summary>
/// The Exterior Gateway Protocol (EGP), a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_EGP = 5,
/// <summary>
/// The Gateway-to-Gateway Protocol (GGP), a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_GGP = 6,
/// <summary>
/// The Hellospeak protocol, a dynamic routing protocol. This is a
/// historical entry no longer in use and was an early routing protocol
/// used by the original ARPANET routers that ran special software
/// called the Fuzzball routing protocol, sometimes called Hellospeak,
/// as described in RFC 891 and RFC 1305. For more information,
/// see http://www.ietf.org/rfc/rfc891.txt and http://www.ietf.org/rfc/rfc1305.txt.
/// </summary>
MIB_IPPROTO_HELLO = 7,
/// <summary>
/// The Berkeley Routing Information Protocol (RIP) or RIP-II, a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_RIP = 8,
/// <summary>
/// The Intermediate System-to-Intermediate System (IS-IS) protocol,
/// a dynamic routing protocol. The IS-IS protocol was developed for
/// use in the Open Systems Interconnection (OSI) protocol suite.
/// </summary>
MIB_IPPROTO_IS_IS = 9,
/// <summary>
/// The End System-to-Intermediate System (ES-IS) protocol, a dynamic
/// routing protocol. The ES-IS protocol was developed for use in the
/// Open Systems Interconnection (OSI) protocol suite.
/// </summary>
MIB_IPPROTO_ES_IS = 10,
/// <summary>
/// The Cisco Interior Gateway Routing Protocol (IGRP), a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_CISCO = 11,
/// <summary>
/// The Bolt, Beranek, and Newman (BBN) Interior Gateway Protocol
/// (IGP) that used the Shortest Path First (SPF) algorithm. This
/// was an early dynamic routing protocol.
/// </summary>
MIB_IPPROTO_BBN = 12,
/// <summary>
/// The Open Shortest Path First (OSPF) protocol, a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_OSPF = 13,
/// <summary>
/// The Border Gateway Protocol (BGP), a dynamic routing protocol.
/// </summary>
MIB_IPPROTO_BGP = 14,
/// <summary>
/// A Windows specific entry added originally by a routing protocol, but which is now static.
/// </summary>
MIB_IPPROTO_NT_AUTOSTATIC = 10002,
/// <summary>
/// A Windows specific entry added as a static route from the routing user interface or a routing command.
/// </summary>
MIB_IPPROTO_NT_STATIC = 10006,
/// <summary>
/// A Windows specific entry added as a static route from the routing
/// user interface or a routing command, except these routes do not cause Dial On Demand (DOD).
/// </summary>
MIB_IPPROTO_NT_STATIC_NON_DOD = 10007
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_IPFORWARDROW
{
public uint dwForwardDest; //destination IP address.
public uint dwForwardMask; //Subnet mask
public uint dwForwardPolicy; //conditions for multi-path route. Unused, specify 0.
public uint dwForwardNextHop; //IP address of the next hop. Own address?
public uint dwForwardIfIndex; //index of interface
public MIB_IPFORWARD_TYPE dwForwardType; //route type
public MIB_IPPROTO dwForwardProto; //routing protocol.
public uint dwForwardAge; //age of route.
public uint dwForwardNextHopAS; //autonomous system number. 0 if not relevant
public int dwForwardMetric1; //-1 if not used (goes for all metrics)
public int dwForwardMetric2;
public int dwForwardMetric3;
public int dwForwardMetric4;
public int dwForwardMetric5;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_IPINTERFACE_ROW
{
public uint Family;
public ulong InterfaceLuid;
public uint InterfaceIndex;
public uint MaxReassemblySize;
public ulong InterfaceIdentifier;
public uint MinRouterAdvertisementInterval;
public uint MaxRouterAdvertisementInterval;
public byte AdvertisingEnabled;
public byte ForwardingEnabled;
public byte WeakHostSend;
public byte WeakHostReceive;
public byte UseAutomaticMetric;
public byte UseNeighborUnreachabilityDetection;
public byte ManagedAddressConfigurationSupported;
public byte OtherStatefulConfigurationSupported;
public byte AdvertiseDefaultRoute;
public uint RouterDiscoveryBehavior;
public uint DadTransmits;
public uint BaseReachableTime;
public uint RetransmitTime;
public uint PathMtuDiscoveryTimeout;
public uint LinkLocalAddressBehavior;
public uint LinkLocalAddressTimeout;
public uint ZoneIndice0, ZoneIndice1, ZoneIndice2, ZoneIndice3, ZoneIndice4, ZoneIndice5, ZoneIndice6, ZoneIndice7,
ZoneIndice8, ZoneIndice9, ZoneIndice10, ZoneIndice11, ZoneIndice12, ZoneIndice13, ZoneIndice14, ZoneIndice15;
public uint SitePrefixLength;
public uint Metric;
public uint NlMtu;
public byte Connected;
public byte SupportsWakeUpPatterns;
public byte SupportsNeighborDiscovery;
public byte SupportsRouterDiscovery;
public uint ReachableTime;
public byte TransmitOffload;
public byte ReceiveOffload;
public byte DisableDefaultRoutes;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct MIB_IPFORWARDTABLE
{
/// <summary>
/// number of route entriesin the table.
/// </summary>
public int dwNumEntries;
public MIB_IPFORWARDROW table;
}
[DllImport("Iphlpapi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
private static extern int CreateIpForwardEntry(MIB_IPFORWARDROW pRoute);
[DllImport("Iphlpapi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
private static extern int DeleteIpForwardEntry(MIB_IPFORWARDROW pRoute);
[DllImport("Iphlpapi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
private static extern int SetIpForwardEntry(MIB_IPFORWARDROW pRoute);
[DllImport("Iphlpapi.dll")]
private static extern int GetIpInterfaceEntry(ref MIB_IPINTERFACE_ROW row);
[DllImport("iphlpapi.dll", CharSet = CharSet.Auto)]
private static extern int GetBestInterface(uint DestAddr, out uint BestIfIndex);
[DllImport("Iphlpapi.dll")]
private static extern int GetBestRoute(uint dwDestAddr, uint dwSourceAddr, out MIB_IPFORWARDROW pBestRoute);
[DllImport("Iphlpapi.dll")]
[return: MarshalAs(UnmanagedType.U4)]
private unsafe static extern int GetIpForwardTable(MIB_IPFORWARDTABLE* pIpForwardTable, ref int pdwSize, bool bOrder);
[DllImport("Kernel32.dll")]
private extern static int FormatMessage(int flag, ref IntPtr source, int msgid, int langid, ref string buf, int size, ref IntPtr args);
/// <summary>
/// 获取错误信息
/// </summary>
/// <param name="errCode"></param>
/// <returns></returns>
public static string GetErrMsg(int errCode)
{
IntPtr tempptr = IntPtr.Zero;
string msg = null;
FormatMessage(0x1300, ref tempptr, errCode, 0, ref msg, 255, ref tempptr);
return msg;
}
/// <summary>
/// 获取路由表
/// </summary>
/// <param name="ipForwardTable"></param>
/// <returns></returns>
public unsafe static int GetIpForwardTable(out Route[] ipForwardTable)
{
int res = 0, size = 0;
size = Marshal.SizeOf(typeof(MIB_IPFORWARDROW));
MIB_IPFORWARDTABLE* table = (MIB_IPFORWARDTABLE*)Marshal.AllocHGlobal(size);
res = GetIpForwardTable(table, ref size, true);
if (res == 0x7A)
{
table = (MIB_IPFORWARDTABLE*)Marshal.ReAllocHGlobal((IntPtr)table, (IntPtr)size);
res = GetIpForwardTable(table, ref size, true);
}
if (res == 0)
{
ipForwardTable = new Route[(*table).dwNumEntries];
for (int i = 0; i < ipForwardTable.Length; i++)
{
ipForwardTable[i] = new Route((&(*table).table)[i]);
}
}
else
ipForwardTable = null;
Marshal.FreeHGlobal((IntPtr)table);
return res;
}
/// <summary>
/// 获取基础路由
/// </summary>
/// <param name="destAddr"></param>
/// <param name="sourceAddr"></param>
/// <param name="bestRoute"></param>
/// <returns></returns>
public static int GetBestRoute(IPAddress destAddr, IPAddress sourceAddr, out Route bestRoute)
{
MIB_IPFORWARDROW pBestRoute;
var res = GetBestRoute(IpToUint(destAddr), IpToUint(sourceAddr), out pBestRoute);
bestRoute = new Route(pBestRoute);
return res;
}
/// <summary>
/// 获取基础接口
/// </summary>
/// <param name="destAddr"></param>
/// <param name="bestIfIndex"></param>
/// <returns></returns>
public static int GetBestInterface(IPAddress destAddr, out uint bestIfIndex)
{
return GetBestInterface(IpToUint(destAddr), out bestIfIndex);
}
/// <summary>
/// 获取IP接口信息
/// </summary>
/// <param name="interfaceIndex"></param>
/// <param name="row"></param>
/// <returns></returns>
public static int GetIpInterfaceEntry(uint interfaceIndex, out MIB_IPINTERFACE_ROW row)
{
row = new MIB_IPINTERFACE_ROW();
row.Family = 2;
//row.InterfaceLuid = 0;
row.InterfaceIndex = interfaceIndex;
return GetIpInterfaceEntry(ref row);
}
/// <summary>
/// 获取单条路由信息
/// </summary>
/// <param name="destAddr"></param>
/// <param name="nextHop"></param>
/// <param name="route"></param>
/// <returns></returns>
public unsafe static int GetIpForwardEntry(IPAddress destAddr, IPAddress nextHop, out Route route)
{
route = null;
Route[] ipForwardTable;
var res = GetIpForwardTable(out ipForwardTable);
if (res == 0)
{
for (int i = 0; i < ipForwardTable.Length; i++)
{
if (ipForwardTable[i].Destination.Equals(destAddr) && ipForwardTable[i].NextHop.Equals(nextHop))
{
route = ipForwardTable[i];
break;
}
}
}
return res;
}
/// <summary>
/// 获取单条路由信息
/// </summary>
/// <param name="destAddr"></param>
/// <param name="route"></param>
/// <returns></returns>
public unsafe static int GetIpForwardEntry(IPAddress destAddr, out Route route)
{
route = null;
Route[] ipForwardTable;
var res = GetIpForwardTable(out ipForwardTable);
if (res == 0)
{
for (int i = 0; i < ipForwardTable.Length; i++)
{
if (ipForwardTable[i].Destination.Equals(destAddr))
{
route = ipForwardTable[i];
break;
}
}
}
return res;
}
/// <summary>
/// 创建路由
/// </summary>
/// <param name="route"></param>
/// <returns></returns>
public static int CreateIpForwardEntry(Route route)
{
return CreateIpForwardEntry(route.GetBaseStruct());
}
/// <summary>
/// 创建路由
/// </summary>
/// <param name="dest"></param>
/// <param name="mask"></param>
/// <param name="nextHop"></param>
/// <param name="ifIndex"></param>
/// <param name="metric"></param>
/// <returns></returns>
public static int CreateIpForwardEntry(IPAddress dest, IPAddress mask, IPAddress nextHop, uint ifIndex, int metric = 1)
{
Route route = new Route()
{
Destination = dest,
Mask = mask,
NextHop = nextHop,
IfIndex = ifIndex,
Metric = metric,
Policy = 0,
Type = MIB_IPFORWARD_TYPE.MIB_IPROUTE_TYPE_DIRECT,
Proto = MIB_IPPROTO.MIB_IPPROTO_NETMGMT,
Age = 0,
NextHopAS = 0
};
OperatingSystem os = Environment.OSVersion;
if (os.Platform == PlatformID.Win32NT && os.Version.Major >= 6)
{
MIB_IPINTERFACE_ROW row;
int res = GetIpInterfaceEntry(ifIndex, out row);
if (res != 0)
return res;
route.Metric = (int)row.Metric;
}
return CreateIpForwardEntry(route);
}
/// <summary>
/// 创建路由
/// </summary>
/// <param name="dest"></param>
/// <param name="mask"></param>
/// <param name="nextHop"></param>
/// <param name="metric"></param>
/// <returns></returns>
public static int CreateIpForwardEntry(IPAddress dest, IPAddress mask, IPAddress nextHop, int metric = 1)
{
uint bestIfIndex;
int res = GetBestInterface(nextHop, out bestIfIndex);
if (res != 0)
return res;
return CreateIpForwardEntry(dest, mask, nextHop, bestIfIndex, metric);
}
/// <summary>
/// 创建路由
/// </summary>
/// <param name="dest"></param>
/// <param name="nextHop"></param>
/// <param name="metric"></param>
/// <returns></returns>
public static int CreateIpForwardEntry(IPAddress dest, IPAddress nextHop, int metric = 1)
{
return CreateIpForwardEntry(dest, IPAddress.Parse("255.255.255.255"), nextHop, metric);
}
/// <summary>
/// [不推荐使用]修改路由
/// 仅用于修改网关和跃点数
/// </summary>
/// <param name="route"></param>
/// <returns></returns>
public static int SetIpForwardEntry(Route route)
{
return SetIpForwardEntry(route.GetBaseStruct());
}
/// <summary>
/// 删除路由
/// </summary>
/// <param name="route"></param>
/// <returns></returns>
public static int DeleteIpForwardEntry(Route route)
{
return DeleteIpForwardEntry(route.GetBaseStruct());
}
/// <summary>
/// 删除路由
/// </summary>
/// <param name="destAddr"></param>
/// <param name="nextHop"></param>
/// <returns></returns>
public static int DeleteIpForwardEntry(IPAddress destAddr, IPAddress nextHop)
{
Route route;
int res = GetIpForwardEntry(destAddr, nextHop, out route);
if (res != 0)
return res;
return DeleteIpForwardEntry(route);
}
/// <summary>
/// 删除路由
/// </summary>
/// <param name="destAddr"></param>
/// <returns></returns>
public static int DeleteIpForwardEntry(IPAddress destAddr)
{
Route route;
int res = GetIpForwardEntry(destAddr, out route);
if (res != 0)
return res;
return DeleteIpForwardEntry(route);
}
/// <summary>
/// IPAdderss转uint
/// </summary>
/// <param name="ipAddress"></param>
/// <returns></returns>
public static uint IpToUint(IPAddress ipAddress)
{
string[] startIP = ipAddress.ToString().Split('.');
uint U = uint.Parse(startIP[3]) << 24;
U += uint.Parse(startIP[2]) << 16;
U += uint.Parse(startIP[1]) << 8;
U += uint.Parse(startIP[0]);
return U;
}
/// <summary>
/// uint转IPAddress
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static IPAddress UintToIp(uint ip)
{
string ipStr = $"{ip & 0xff}.{(ip >> 8) & 0xff}.{(ip >> 16) & 0xff}.{(ip >> 24) & 0xff}";
return IPAddress.Parse(ipStr);
}
}
}