-
Notifications
You must be signed in to change notification settings - Fork 28
/
Ping.cs
393 lines (333 loc) · 17 KB
/
Ping.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
/*
MIT License - PowerPing
Copyright (c) 2019 Matthew Carney
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace PowerPing
{
/// <summary>
/// Ping Class, used for constructing and sending ICMP packets.
/// </summary>
class Ping
{
private static readonly ushort m_SessionId = Helper.GenerateSessionId();
private readonly CancellationToken m_CancellationToken;
private bool m_Debug = false;
public Ping(CancellationToken cancellationTkn)
{
m_CancellationToken = cancellationTkn;
}
/// <summary>
/// Sends a set of ping packets, results are stores within
/// Ping.Results of the called object
///
/// Acts as a basic wrapper to SendICMP and feeds it a specific
/// set of PingAttributes
/// </summary>
public PingResults Send(PingAttributes attrs, Action<PingResults> onResultsUpdate = null)
{
// Lookup host if specified
if (attrs.InputtedAddress != "") {
attrs.Address = PowerPing.Lookup.QueryDNS(attrs.InputtedAddress, attrs.ForceV4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6);
}
PowerPing.Display.PingIntroMsg(attrs);
if (Display.UseResolvedAddress) {
try {
attrs.InputtedAddress = Helper.RunWithCancellationToken(() => Lookup.QueryHost(attrs.Address), m_CancellationToken);
} catch (OperationCanceledException) {
return new PingResults();
}
if (attrs.InputtedAddress == "") {
// If reverse lookup fails just display whatever is in the address field
attrs.InputtedAddress = attrs.Address;
}
}
// Perform ping operation and store results
PingResults results = SendICMP(attrs, onResultsUpdate);
if (Display.ShowOutput) {
PowerPing.Display.PingResults(attrs, results);
}
return results;
}
/// <summary>
/// Listens for all ICMPv4 activity on localhost.
///
/// Does this by setting a raw socket to SV_IO_ALL which
/// will recieve all packets and filters to just show
/// ICMP packets. Runs until ctrl-c or exit
/// </summary>
/// <source>https://stackoverflow.com/a/9174392</source>
public void Listen()
{
IPAddress localAddress = null;
Socket listeningSocket = null;
PingResults results = new PingResults();
// Find local address
localAddress = IPAddress.Parse(PowerPing.Lookup.LocalAddress());
try {
// Create listener socket
listeningSocket = CreateRawSocket(AddressFamily.InterNetwork);
listeningSocket.Bind(new IPEndPoint(localAddress, 0));
listeningSocket.IOControl(IOControlCode.ReceiveAll, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0, 0, 0 }); // Set SIO_RCVALL flag to socket IO control
PowerPing.Display.ListenIntroMsg();
// Listening loop
while (!m_CancellationToken.IsCancellationRequested) {
byte[] buffer = new byte[4096]; // TODO: could cause overflow?
// Recieve any incoming ICMPv4 packets
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = Helper.RunWithCancellationToken(() => listeningSocket.ReceiveFrom(buffer, ref remoteEndPoint), m_CancellationToken);
ICMP response = new ICMP(buffer, bytesRead);
// Display captured packet
PowerPing.Display.CapturedPacket(response, remoteEndPoint.ToString(), DateTime.Now.ToString("h:mm:ss.ff tt"), bytesRead);
// Store results
results.CountPacketType(response.Type);
results.Received++;
}
} catch (OperationCanceledException) {
} catch (SocketException) {
PowerPing.Display.Error("Could not read packet from socket");
} catch (Exception e) {
PowerPing.Display.Error($"General exception occured while trying to create listening socket (Exception: {e.GetType().ToString().Split('.').Last()}");
}
// Clean up
listeningSocket.Close();
// TODO: Implement ListenResults method
//Display.ListenResults(results);
}
/// <summary>
/// ICMP Traceroute
/// Not implemented yet
/// </summary>
public void Trace() { throw new NotSupportedException(); }
/// <summary>
/// Creates a raw socket for ping operations.
///
/// We have to use raw sockets here as we are using our own
/// implementation of ICMP and only raw sockets will allow us
/// to send whatever data we want through it.
///
/// The downside is this is why we need to run as administrator
/// but it allows us the greater degree of control over the packets
/// that we need
/// </summary>
/// <param name="family">AddressFamily to use (IP4 or IP6)</param>
/// <returns>A raw socket</returns>
private static Socket CreateRawSocket(AddressFamily family)
{
Socket s = null;
try {
s = new Socket(family, SocketType.Raw, family == AddressFamily.InterNetwork ? ProtocolType.Icmp : ProtocolType.IcmpV6);
} catch (SocketException) {
PowerPing.Helper.ErrorAndExit("Socket cannot be created " + Environment.NewLine + "Please run as Administrator and try again.");
}
return s;
}
/// <summary>
/// Core ICMP sending method (used by all other functions)
/// Takes a set of attributes, performs operation and returns a set of results.
///
/// Works specifically by creating a raw socket, creating a ICMP object and
/// other socket properties (timeouts, interval etc) using the
/// inputted properties (attrs), then performs ICMP operation
/// before cleaning up and returning results.
///
/// </summary>
/// <param name="attrs">Properties of pings to be sent</param>
/// <param name="resultsUpdateCallback">Method to call after each iteration</param>
/// <returns>Set of ping results</returns>
private PingResults SendICMP(PingAttributes attrs, Action<PingResults> resultsUpdateCallback = null)
{
PingResults results = new PingResults();
ICMP packet = new ICMP();
byte[] receiveBuffer = new byte[attrs.RecieveBufferSize]; // Ipv4Header.length + IcmpHeader.length + attrs.recievebuffersize
int bytesRead, packetSize;
// Convert to IPAddress
IPAddress ipAddr = IPAddress.Parse(attrs.Address);
// Setup endpoint
IPEndPoint iep = new IPEndPoint(ipAddr, 0);
// Setup raw socket
Socket sock = CreateRawSocket(ipAddr.AddressFamily);
// Helper function to set receive timeout (only if it's changing)
int appliedReceiveTimeout = 0;
void SetReceiveTimeout(int receiveTimeout) {
if (receiveTimeout != appliedReceiveTimeout) {
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, receiveTimeout);
appliedReceiveTimeout = receiveTimeout;
}
}
// Set socket options
sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, attrs.Ttl);
sock.DontFragment = attrs.DontFragment;
// Create packet message payload
byte[] payload;
if (attrs.Size != -1) {
payload = Helper.GenerateByteArray(attrs.Size);
} else {
payload = Encoding.ASCII.GetBytes(attrs.Message);
}
// Construct our ICMP packet
packet.Type = attrs.Type;
packet.Code = attrs.Code;
Buffer.BlockCopy(BitConverter.GetBytes(m_SessionId), 0, packet.Message, 0, 2); // Add identifier to ICMP message
Buffer.BlockCopy(payload, 0, packet.Message, 4, payload.Length); // Add text into ICMP message
packet.MessageSize = payload.Length + 4;
packetSize = packet.MessageSize + 4;
// Sending loop
for (int index = 1; attrs.Continous || index <= attrs.Count; index++) {
if (index != 1) {
// Wait for set interval before sending again or cancel if requested
if (m_CancellationToken.WaitHandle.WaitOne(attrs.Interval)) {
break;
}
// Generate random interval when RandomTimings flag is set
if (attrs.RandomTiming) {
attrs.Interval = Helper.RandomInt(5000, 100000);
}
}
// Include sequence number in ping message
ushort sequenceNum = (ushort)index;
Buffer.BlockCopy(BitConverter.GetBytes(sequenceNum), 0, packet.Message, 2, 2);
// Fill ICMP message field
if (attrs.RandomMsg) {
payload = Encoding.ASCII.GetBytes(Helper.RandomString());
Buffer.BlockCopy(payload, 0, packet.Message, 4, payload.Length);
}
// Update packet checksum
packet.Checksum = 0;
UInt16 chksm = packet.GetChecksum();
packet.Checksum = chksm;
try {
// Show request packet
if (Display.ShowRequests) {
Display.RequestPacket(packet, Display.UseInputtedAddress | Display.UseResolvedAddress ? attrs.InputtedAddress : attrs.Address, index);
}
// If there were extra responses from a prior request, ignore them
while (sock.Available != 0) {
bytesRead = sock.Receive(receiveBuffer);
}
// Send ping request
sock.SendTo(packet.GetBytes(), packetSize, SocketFlags.None, iep); // Packet size = message field + 4 header bytes
long requestTimestamp = Stopwatch.GetTimestamp();
try { results.Sent++; }
catch (OverflowException) { results.HasOverflowed = true; }
if (m_Debug) {
// Induce random wait for debugging
Random rnd = new Random();
Thread.Sleep(rnd.Next(700));
if (rnd.Next(20) == 1) { throw new SocketException(); }
}
ICMP response;
EndPoint responseEP = iep;
TimeSpan replyTime = TimeSpan.Zero;
do {
// Cancel if requested
m_CancellationToken.ThrowIfCancellationRequested();
// Set receive timeout, limited to 250ms so we don't block very long without checking for
// cancellation. If the requested ping timeout is longer, we will wait some more in subsequent
// loop iterations until the requested ping timeout is reached.
int remainingTimeout = (int)Math.Ceiling(attrs.Timeout - replyTime.TotalMilliseconds);
if (remainingTimeout <= 0) {
throw new SocketException();
}
SetReceiveTimeout(Math.Min(remainingTimeout, 250));
// Wait for response
try {
bytesRead = sock.ReceiveFrom(receiveBuffer, ref responseEP);
} catch (SocketException) {
bytesRead = 0;
}
replyTime = new TimeSpan(Helper.StopwatchToTimeSpanTicks(Stopwatch.GetTimestamp() - requestTimestamp));
if (bytesRead == 0) {
response = null;
} else {
// Store reply packet
response = new ICMP(receiveBuffer, bytesRead);
// If we sent an echo and receive a response with a different identifier or sequence
// number, ignore it (it could correspond to an older request that timed out)
if (packet.Type == 8 && response.Type == 0) {
ushort responseSessionId = BitConverter.ToUInt16(response.Message, 0);
ushort responseSequenceNum = BitConverter.ToUInt16(response.Message, 2);
if (responseSessionId != m_SessionId || responseSequenceNum != sequenceNum) {
response = null;
}
}
}
} while (response == null);
// Display reply packet
if (Display.ShowReplies) {
PowerPing.Display.ReplyPacket(response, Display.UseInputtedAddress | Display.UseResolvedAddress ? attrs.InputtedAddress : responseEP.ToString(), index, replyTime, bytesRead);
}
// Store response info
try { results.Received++; }
catch (OverflowException) { results.HasOverflowed = true; }
results.CountPacketType(response.Type);
results.SaveResponseTime(replyTime.TotalMilliseconds);
if (attrs.BeepLevel == 2) {
try { Console.Beep(); }
catch (Exception) { } // Silently continue if Console.Beep errors
}
} catch (IOException) {
if (Display.ShowOutput) {
PowerPing.Display.Error("General transmit error");
}
results.SaveResponseTime(-1);
try { results.Lost++; }
catch (OverflowException) { results.HasOverflowed = true; }
} catch (SocketException) {
PowerPing.Display.Timeout(index);
if (attrs.BeepLevel == 1) {
try { Console.Beep(); }
catch (Exception) { results.HasOverflowed = true; }
}
results.SaveResponseTime(-1);
try { results.Lost++; }
catch (OverflowException) { results.HasOverflowed = true; }
} catch (OperationCanceledException) {
results.ScanWasCanceled = true;
break;
} catch (Exception) {
if (Display.ShowOutput) {
PowerPing.Display.Error("General error occured");
}
results.SaveResponseTime(-1);
try { results.Lost++; }
catch (OverflowException) { results.HasOverflowed = true; }
}
// Run callback (if provided) to notify of updated results
resultsUpdateCallback?.Invoke(results);
}
// Clean up
sock.Close();
return results;
}
public class ActiveHost
{
public string Address { get; set; }
public string HostName { get; set; }
public double ResponseTime { get; set; }
}
}
}