-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
390 lines (343 loc) · 10.8 KB
/
Copy pathProgram.cs
File metadata and controls
390 lines (343 loc) · 10.8 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
385
386
387
388
389
390
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
if (args.Length == 0)
{
Console.Error.WriteLine("Usage: PingMoni <target> [-i <interval_ms>] [-o <log_dir>] [-h|--help]");
Console.Error.WriteLine("Run 'PingMoni --help' for detailed options.");
return 1;
}
if (args.Any(a => a is "-h" or "--help" or "/?"))
{
PrintHelp();
return 0;
}
var target = args[0];
var interval = 1000;
var appDir = Path.GetDirectoryName(Environment.ProcessPath) ?? AppContext.BaseDirectory;
var logDir = Path.Combine(appDir, "PingmoniLogs");
for (var i = 1; i < args.Length; i++)
{
if ((args[i] == "-i" || args[i] == "--interval") && i + 1 < args.Length)
{
if (int.TryParse(args[i + 1], out var val) && val > 0)
{
interval = val;
i++;
}
else
{
Console.Error.WriteLine($"Warning: invalid interval value '{args[i + 1]}', using default {interval}ms.");
i++;
}
}
else if ((args[i] == "-o" || args[i] == "--output") && i + 1 < args.Length)
{
logDir = args[i + 1];
i++;
}
else
{
Console.Error.WriteLine($"Warning: unknown argument '{args[i]}' ignored.");
if (i + 1 < args.Length && !args[i + 1].StartsWith('-'))
i++;
}
}
Directory.CreateDirectory(logDir);
var safeTarget = SanitizeFileName(target);
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
cts.Cancel();
};
var icmpHandle = NativeMethods.IcmpCreateFile();
if (icmpHandle == IntPtr.Zero || icmpHandle == NativeMethods.InvalidHandleValue)
{
Console.Error.WriteLine("Failed to create ICMP handle. Try running as administrator.");
return 1;
}
try
{
bool isDirectIp = IPAddress.TryParse(target, out var parsedIp);
uint ipAddr = 0;
DateTime lastDnsResolve = DateTime.MinValue;
var dnsRefreshInterval = TimeSpan.FromMinutes(5);
if (isDirectIp)
{
ipAddr = BitConverter.ToUInt32(parsedIp!.GetAddressBytes(), 0);
}
else
{
var (dnsOk, initialIp) = await TryResolveDnsAsync(target, cts.Token);
if (!dnsOk)
{
Console.Error.WriteLine("Initial DNS resolution failed. Exiting.");
return 1;
}
ipAddr = initialIp;
lastDnsResolve = DateTime.UtcNow;
}
var sendData = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(sendData);
var sendOpts = new IpOptionInformation { Ttl = 128, Tos = 0, Flags = 0, OptionsSize = 0, OptionsData = IntPtr.Zero };
var replyBuf = new byte[1024];
var ttlOffset = RuntimeInformation.ProcessArchitecture == Architecture.X64 ? 24 : 20;
await using var logWriter = new LogWriter(logDir, safeTarget);
var nextPing = DateTime.UtcNow;
while (!cts.IsCancellationRequested)
{
if (!isDirectIp && (DateTime.UtcNow - lastDnsResolve) > dnsRefreshInterval)
{
var (dnsOk, newIp) = await TryResolveDnsAsync(target, cts.Token);
if (dnsOk)
{
ipAddr = newIp;
lastDnsResolve = DateTime.UtcNow;
}
}
var now = DateTime.Now;
var ts = now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var reply = NativeMethods.IcmpSendEcho(
icmpHandle, ipAddr, sendData, (ushort)sendData.Length,
ref sendOpts, replyBuf, (uint)replyBuf.Length, 4000);
int lastError = Marshal.GetLastPInvokeError();
if (reply > 0)
{
uint status = BitConverter.ToUInt32(replyBuf, 4);
uint rtt = BitConverter.ToUInt32(replyBuf, 8);
ushort dataSize = BitConverter.ToUInt16(replyBuf, 12);
byte ttl = replyBuf[ttlOffset];
var success = status == 0;
var entry = new PingEntry
{
Timestamp = ts,
Target = target,
Latency = (int)rtt,
Status = success ? "success" : "failure",
Details = new PingDetails
{
Bytes = dataSize,
Ttl = ttl
}
};
var line = JsonSerializer.Serialize(entry, AppJsonContext.Default.PingEntry);
await logWriter.WriteAsync(line);
var replyAddr = new IPAddress(BitConverter.GetBytes(BitConverter.ToUInt32(replyBuf, 0)));
if (success)
Console.WriteLine($"[{ts}] Reply from {replyAddr}: bytes={dataSize} time={rtt}ms TTL={ttl}");
else
Console.WriteLine($"[{ts}] Reply from {replyAddr}: status={status}");
}
else
{
var entry = new PingEntry
{
Timestamp = ts,
Target = target,
Latency = 0,
Status = "failure",
Details = new PingDetails
{
Bytes = 0,
Ttl = 0
}
};
var line = JsonSerializer.Serialize(entry, AppJsonContext.Default.PingEntry);
await logWriter.WriteAsync(line);
Console.WriteLine($"[{ts}] Request timed out. (error={lastError})");
}
nextPing = nextPing.AddMilliseconds(interval);
var delay = nextPing - DateTime.UtcNow;
if (delay > TimeSpan.Zero)
{
try
{
await Task.Delay(delay, cts.Token);
}
catch (OperationCanceledException)
{
break;
}
}
else
{
nextPing = DateTime.UtcNow;
}
}
}
finally
{
NativeMethods.IcmpCloseHandle(icmpHandle);
}
return 0;
static async Task<(bool Success, uint IpAddress)> TryResolveDnsAsync(string targetHost, CancellationToken token)
{
try
{
var hostEntry = await Dns.GetHostEntryAsync(targetHost, token);
var ipv4 = hostEntry.AddressList.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);
if (ipv4 == null)
{
Console.Error.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] Warning: Failed to resolve IPv4 address for '{targetHost}'.");
return (false, 0);
}
var ip = BitConverter.ToUInt32(ipv4.GetAddressBytes(), 0);
return (true, ip);
}
catch (Exception ex)
{
Console.Error.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] Warning: DNS resolution failed for '{targetHost}': {ex.Message}");
return (false, 0);
}
}
static string SanitizeFileName(string name)
{
var invalidChars = Path.GetInvalidFileNameChars();
var sanitized = new System.Text.StringBuilder(name.Length);
foreach (var ch in name)
{
sanitized.Append(invalidChars.Contains(ch) ? '_' : ch);
}
return sanitized.ToString();
}
static void PrintHelp()
{
Console.WriteLine("""
PingMoni - Lightweight ICMP Network Monitoring Tool
Usage:
PingMoni <target> [options]
Arguments:
<target> IP address or hostname to ping (e.g. 192.168.1.1 or www.bing.com)
Options:
-i, --interval <ms> Ping interval in milliseconds (default: 1000)
-o, --output <dir> Directory path to store daily JSON log files
(default: <ExeDir>\PingmoniLogs)
-h, --help Show this help message and exit
Examples:
PingMoni www.bing.com
PingMoni 192.168.1.1 -i 500
PingMoni 10.0.0.1 -i 2000 -o D:\NetworkLogs
""");
}
class LogWriter : IAsyncDisposable
{
private readonly string _logDir;
private readonly string _safeTarget;
private string _currentDateStr = "";
private StreamWriter? _writer;
public LogWriter(string logDir, string safeTarget)
{
_logDir = logDir;
_safeTarget = safeTarget;
}
public async Task WriteAsync(string line)
{
var today = DateTime.Now.ToString("yyyy-MM-dd");
if (_writer == null || _currentDateStr != today)
{
await RotateFileAsync(today);
}
if (_writer != null)
{
try
{
await _writer.WriteLineAsync(line);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to write log: {ex.Message}");
}
}
}
private async Task RotateFileAsync(string today)
{
if (_writer != null)
{
try
{
await _writer.DisposeAsync();
}
catch { }
_writer = null;
}
_currentDateStr = today;
var filePath = Path.Combine(_logDir, $"{_safeTarget}_{today}.log");
try
{
var stream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 4096, useAsync: true);
_writer = new StreamWriter(stream, System.Text.Encoding.UTF8) { AutoFlush = true };
}
catch (Exception ex)
{
Console.Error.WriteLine($"Failed to open log file '{filePath}': {ex.Message}");
}
}
public async ValueTask DisposeAsync()
{
if (_writer != null)
{
try
{
await _writer.DisposeAsync();
}
catch { }
_writer = null;
}
}
}
[StructLayout(LayoutKind.Sequential)]
struct IpOptionInformation
{
public byte Ttl;
public byte Tos;
public byte Flags;
public byte OptionsSize;
public IntPtr OptionsData;
}
static class NativeMethods
{
public static readonly IntPtr InvalidHandleValue = new IntPtr(-1);
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern IntPtr IcmpCreateFile();
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern bool IcmpCloseHandle(IntPtr handle);
[DllImport("iphlpapi.dll", SetLastError = true)]
public static extern uint IcmpSendEcho(
IntPtr icmpHandle,
uint destinationAddress,
byte[] requestData,
ushort requestSize,
ref IpOptionInformation requestOptions,
byte[] replyBuffer,
uint replySize,
uint timeout);
}
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(PingEntry))]
[JsonSerializable(typeof(PingDetails))]
internal partial class AppJsonContext : JsonSerializerContext
{
}
record PingEntry
{
[JsonPropertyOrder(1)]
public string Timestamp { get; init; } = "";
[JsonPropertyOrder(2)]
public string Target { get; init; } = "";
[JsonPropertyOrder(3)]
public int Latency { get; init; }
[JsonPropertyOrder(4)]
public string Status { get; init; } = "";
[JsonPropertyOrder(5)]
public PingDetails Details { get; init; } = new();
}
record PingDetails
{
[JsonPropertyOrder(1)]
public int Bytes { get; init; }
[JsonPropertyOrder(2)]
public int Ttl { get; init; }
}