Repository navigation
Expand file tree
/
Copy pathTraceroute.cs
More file actions
180 lines (138 loc) · 5.75 KB
/
Copy pathTraceroute.cs
File metadata and controls
180 lines (138 loc) · 5.75 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using NETworkManager.Models.IPApi;
using NETworkManager.Utilities;
namespace NETworkManager.Models.Network;
public sealed class Traceroute
{
#region Variables
private readonly TracerouteOptions _options;
// Data sent with the ping, created once (see TracerouteOptions.BufferSize)
private readonly byte[] _buffer;
#endregion
#region Constructor
public Traceroute(TracerouteOptions options)
{
_options = options;
_buffer = new byte[options.BufferSize];
}
#endregion
#region Methods
public void TraceAsync(IPAddress ipAddress, CancellationToken cancellationToken)
{
Task.Run(async () =>
{
try
{
for (var i = 1; i < _options.MaximumHops + 1; i++)
{
var tasks = new List<Task<Tuple<PingReply, long>>>();
// Send 3 pings
for (var y = 0; y < 3; y++)
{
var i1 = i;
tasks.Add(Task.Run(() =>
{
var stopwatch = new Stopwatch();
PingReply pingReply;
using (var ping = new System.Net.NetworkInformation.Ping())
{
stopwatch.Start();
pingReply = ping.Send(ipAddress, _options.Timeout, _buffer,
new PingOptions { Ttl = i1, DontFragment = _options.DontFragment });
stopwatch.Stop();
}
return Tuple.Create(pingReply, stopwatch.ElapsedMilliseconds);
}, cancellationToken));
}
try
{
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException ex)
{
// Remove duplicate messages
OnTraceError(new TracerouteErrorArgs(string.Join(", ",
ex.Flatten().InnerExceptions.Select(s => s.Message).Distinct())));
return;
}
// Check results -> Get IP on success or TTL expired
var ipAddressHop = (from task in tasks
where task.Result.Item1.Status != IPStatus.TimedOut
where task.Result.Item1.Status is IPStatus.TtlExpired or IPStatus.Success
select task.Result.Item1.Address).FirstOrDefault();
// Resolve Hostname
var hostname = string.Empty;
if (_options.ResolveHostname && ipAddressHop != null)
{
var dnsResult = await DNSClient.GetInstance().ResolvePtrAsync(ipAddressHop);
if (!dnsResult.HasError)
hostname = dnsResult.Value;
}
IPGeolocationResult ipGeolocationResult = null;
// Get IP geolocation info
if (_options.CheckIPApiIPGeolocation && ipAddressHop != null &&
!IPAddressHelper.IsPrivateIPAddress(ipAddressHop))
ipGeolocationResult =
await IPGeolocationService.GetInstance().GetIPGeolocationAsync($"{ipAddressHop}");
OnHopReceived(new TracerouteHopReceivedArgs(new TracerouteHopInfo(i,
tasks[0].Result.Item1.Status, tasks[0].Result.Item2,
tasks[1].Result.Item1.Status, tasks[1].Result.Item2,
tasks[2].Result.Item1.Status, tasks[2].Result.Item2,
ipAddressHop, hostname, ipGeolocationResult ?? new IPGeolocationResult())));
// Check if finished
if (ipAddressHop != null && ipAddress.ToString() == ipAddressHop.ToString())
{
OnTraceComplete();
return;
}
// Check for cancel
if (!cancellationToken.IsCancellationRequested)
continue;
OnUserHasCanceled();
return;
}
// Max hops reached...
OnMaximumHopsReached(new MaximumHopsReachedArgs(_options.MaximumHops));
}
catch (Exception ex)
{
OnTraceError(new TracerouteErrorArgs(ex.Message));
}
}, cancellationToken);
}
#endregion
#region Events
public event EventHandler<TracerouteHopReceivedArgs> HopReceived;
private void OnHopReceived(TracerouteHopReceivedArgs e)
{
HopReceived?.Invoke(this, e);
}
public event EventHandler TraceComplete;
private void OnTraceComplete()
{
TraceComplete?.Invoke(this, EventArgs.Empty);
}
public event EventHandler<MaximumHopsReachedArgs> MaximumHopsReached;
private void OnMaximumHopsReached(MaximumHopsReachedArgs e)
{
MaximumHopsReached?.Invoke(this, e);
}
public event EventHandler<TracerouteErrorArgs> TraceError;
private void OnTraceError(TracerouteErrorArgs e)
{
TraceError?.Invoke(this, e);
}
public event EventHandler UserHasCanceled;
private void OnUserHasCanceled()
{
UserHasCanceled?.Invoke(this, EventArgs.Empty);
}
#endregion
}