-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
1822 lines (1719 loc) · 107 KB
/
Program.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************
* Pinger - Advanced command line ping tool
* Copyright (c) 2024 Teiva Rodiere
* https://github.com/teivarodiere/pinger
*************************************************************************/
// pinger Utility
// use 'pinger.exe /?' for help+
using System;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;
using System.Xml.Serialization;
using System.Net.Sockets;
using System.ComponentModel;
using System.Reflection;
using System.Diagnostics;
using System.Security.Permissions;
using System.Globalization;
using System.Formats.Tar;
namespace Pinger
{
public enum MessageBeepType
{
//Default = -1,
Ok = 262,
Error = 311,
// Question = 0x00000020,
// Warning = 0x00000030,
//Information = 0x00000040,
}
public enum ResultCodes
{
//Default = -1,
Ok = 0,
Error = 1
}
public enum DnsLookupByCodes
{
ByIP = 0,
ByName = 1
}
static class Globals
{
public static bool PROGRAM_VERBOSE = false; // false by default. Verbose on screen
public static bool PROGRAM_VERBOSE_LEVEL1 = false; // false by default. Verbose more on screen
public static bool PROGRAM_VERBOSE_LEVEL2 = false; // false by default. Verbose more on screen
public static ResultCodes RUNTIME_ERROR = ResultCodes.Ok; // OK no errors by default. The latest error is stored in this variable
// Ping for a number of counts
public static bool MAX_COUNT_USER_SPECIFIED = false; // false by default. How many times the user requested to ping a specific target host
public static double PING_COUNT_RUNTIME_VALUE = 0; // 0 by default. Keep track of the current ping count per host
public static double PING_COUNT_VALUE_USER_SPECIFIED = 0; // 0 by default. The number of times the user requested to ping a host
public static bool VERBOSE = false; // false by default. ot sure
public static bool PING_ALL_IP_ADDRESSES = false; // false by default. If a hostname is specified, and the DNS resolve to multiple IP addresses, set to true to ping all it's IPs, or false to ping the first returned IP
public static bool PING_ONLY_DNS_RESOLVABLE_TARGETS = false; // false by default. If you wish to pinger to ping only DNS resolvable systems, set this to true
public static bool IPV4_ONLY_IF = false; // false by default. The user is only requesting to ping IPv4 addresses. NOTE: DNS lookup may resolve hosts to IPv6 or the user can pass on to pinger an IPv6 address. Setting this variable to true, skips IPv6 addresses
public static bool IPV6_ONLY_IF = false; // false by default. The user is only requesting to ping IPv4 addresses. NOTE: DNS lookup may resolve hosts to IPv6 or the user can pass on to pinger an IPv6 address. Setting this variable to true, skips IPv6 addresses
public static bool ENABLE_CONTINEOUS_PINGS = false; // false by default. When true, pinger pings like standard pint, aka contenously.
public static bool SILENCE_AUDIBLE_ALARM = false; // false by default. Do not issue 4 Beeps on failed ping, and 2 Beeps on successfull beeps. Beeps work on Windows and Macs, but on Mac only hear 1 beep regardless.
public static int BEEP_COUNTS_SUCCESSFULL = 2; // 2 by default. The console will beep this many times to alert of a successfull ping reply
public static int BEEP_COUNTS_UNSUCCESSFULL = 4; // 4 by default. The console will beep this many times to alert of a unsuccessfull ping reply
public static bool PRINT_NEW_LINE = false; // false by default. Do not print a new line in some cases in the console output - not recommended to set to true. Don't know why it's an option still
public static bool FORCE_SLEEP = true; // true by default. overrides pinger from sleeping 1 second between a ping response and the next ping. This will increase the ping rate to potentially.
public static int SLEEP_IN_USER_REQUESTED_IN_SECONDS = 1; // 1 by default. pinger will 'try' to ping host every set time in seconds specified in SLEEP_IN_USER_REQUESTED_IN_SECONDS.
public static int DEFAULT_POLLING_MILLISECONDS = 1000; // 1000 by default. Tells the script to ping in ms or can be seen as polling, not how long to wait for a response
public static int DEFAULT_PING_TIME_TO_LEAVE = 64; // 128 by default. Tells the script to ping in ms or can be seen as polling, not how long to wait for a response
public static int DEFAULT_TIMEOUT_MILLISECONDS = 1000; // 120 milliseconds of amount of time in ms to wait for the ping reply - matches regular ping on windows
public static int SLEEP_IN_USER_REQUESTED_IN_MILLISECONDS = Globals.DEFAULT_POLLING_MILLISECONDS;
public static bool DURATION_USER_SPECIFIED = false;
public static double DURATION_VALUE_USER_SPECIFIED = 0;
public static double DURATION_VALUE_IN_DECIMAL = 0;
public static DateTime DURATION_END_DATE;
public static TimeSpan DURATION_TIMESPAN;
public static bool OUTPUT_SCREEN_TO_CSV = false;
public static bool OUTPUT_ALL_TO_CSV = false;
public static bool SKIP_DNS_LOOKUP = false;
public static string DNS_SERVER = "";
public static string SEPARATOR_CHAR = ","; // this string will be used to separate the output
public static string SUCCESS_STATUS_STRING = "Success";
public static string TIMEDOUT_STATUS_STRING = "NoReply";
public static string OTHER_STATUS_STRING = "Other";
}
public class BackgroundBeep
{
static Thread _beepThread;
static AutoResetEvent _signalBeep;
public enum MessageBeepType
{
//Default = -1,
Ok = 262,
Error = 311,
// Question = 0x00000020,
// Warning = 0x00000030,
//Information = 0x00000040,
}
static BackgroundBeep()
{
_signalBeep = new AutoResetEvent(false);
_beepThread = new Thread(() =>
{
for (; ; )
{
_signalBeep.WaitOne();
if (OperatingSystem.IsWindows())
{
Console.Beep(311, 1600);
}
}
}, 1);
_beepThread.IsBackground = true;
_beepThread.Start();
}
public static void Beep()
{
_signalBeep.Set();
}
}
public class DnsHostObject
{
public required string LookupString { get; set; }
public int Index { get; set; }
public string? HostName { get; set; }
public string? DnsResolvedHostname { get; set; }
public bool Skip { get; set; }
public System.Net.IPAddress[] IPAddresses { get; set; }
public string[]? Aliases { get; set; }
public string? DnsLookUpMessage { get; set; }
public ResultCodes DnsLookUpCode { get; set; }
public DnsLookupByCodes DnsLookupType { get; set; }
[System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute]
public DnsHostObject(string newLookString)
{
LookupString = newLookString;
}
public void Printout()
{
string subsection = "DnsHostObject->Printout()";
//System.Reflection.MethodBase.GetCurrentMethod().MethodHandle.ToString();
Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop);
Console.WriteLine("[VERBOSE][" + subsection + "] _LookupString = " + LookupString);
Console.WriteLine("[VERBOSE][" + subsection + "] Index = " + Index);
Console.WriteLine("[VERBOSE][" + subsection + "] HostName=" + DnsResolvedHostname);
Console.WriteLine("[VERBOSE][" + subsection + "] DnsLookUpMessage=" + DnsLookUpMessage);
Console.WriteLine("[VERBOSE][" + subsection + "] DnsLookUpCode=" + DnsLookUpCode);
Console.WriteLine("[VERBOSE][" + subsection + "] DnsLookupType=" + DnsLookupType);
Console.WriteLine("[VERBOSE][" + subsection + "] Skip=" + Skip);
if (DnsLookUpCode == ResultCodes.Ok)
{
int ipIndex = 1;
foreach (System.Net.IPAddress ip in IPAddresses)
{
Console.WriteLine("[VERBOSE][DnsHostObject] IP" + ipIndex + "=" + ip.ToString() + "[" + ip.AddressFamily + "]");
ipIndex++;
}
}
else
{
Console.WriteLine("[VERBOSE][DnsHostObject] No IPAddresses");
}
}
}
public class DateRange {
public int Index {get; set;}
public DateTime Start {get; set;}
public DateTime End {get; set;}
}
public class PingerTarget
{
public required int TargetIndex { get; set; }
public required string LookupString { get; set; }
private string _DnsResolvedHostname;
private string _DisplayName;
public System.Net.IPAddress? IPAddress { get; set; }
private string dnsReplyIPaddr;
private bool skip;
private long pingReplyRoundTripInMiliSec;
private ResultCodes _DnsLookupStatus;
public string? DnsLookupMessage { get; set; }
private string logFile;
private string errorMsg;
private int errorCode;
private int optionsTtl;
private int hostUnreachableCount;
public List<DateRange> UnreachableDates { get; private set; }
private TimeSpan hostUnreachableTimespan;
private TimeSpan hostReachableTimespan;
private int hostReachableCount;
private DateTime startDate;
private DateTime endDate;
private IPStatus currHostPingStatus;
private int currHostPingCount;
private DateTime currStatusPingDateCurrent;
private DateTime currStatusPingDatePrevious;
private IPStatus prevHostPingStatus;
private DateTime prevStatusPingDate;
private int prevStatusPingCount;
private DnsLookupByCodes _DnsLookupType;
private bool pingByIP;
private string parentTarget;
[System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute]
public PingerTarget(string targetName, int targetIndex)
{
LookupString = targetName;
TargetIndex = targetIndex;
UnreachableDates = new List<DateRange>();
this.Startdate = DateTime.Now;
this.currStatusPingDateCurrent = DateTime.Now;
this.currStatusPingDatePrevious = DateTime.Now;
this.prevStatusPingDate = DateTime.Now;
this._DnsResolvedHostname = "-";
this._DisplayName = "-";
//this._Dnsipaddr = "-";
this.dnsReplyIPaddr = "-";
this.pingReplyRoundTripInMiliSec = -1;
this.skip = false;
//this._DnsLookupStatus = ResultCodes.OK;
this.logFile = "-";
this.currHostPingStatus = IPStatus.Success;
this.prevHostPingStatus = IPStatus.Unknown;
this.errorMsg = "-";
this.optionsTtl = -1;
this.errorCode = -1; // No Errors
this.hostUnreachableCount = 0;
this.hostReachableCount = 0;
this.currHostPingCount = 0;
this.prevStatusPingCount = 0;
//this._DnsLookupType = ;
this.pingByIP = false;
this.parentTarget = "-";
}
public string DisplayName
{
get { return _DisplayName; }
set { _DisplayName = value; }
}
public string ParentTarget
{
get { return parentTarget; }
set { parentTarget = value; }
}
public string DnsResolvedHostname
{
get { return _DnsResolvedHostname; }
set { _DnsResolvedHostname = value; }
}
public bool Skip
{
get { return skip; }
set { skip = value; }
}
public ResultCodes DnsLookupStatus
{
get { return _DnsLookupStatus; }
set { _DnsLookupStatus = value; }
}
public DnsLookupByCodes DnsLookupType
{
get { return _DnsLookupType; }
set { _DnsLookupType = value; }
}
public string LogFile
{
get { return logFile; }
set { logFile = value; }
}
public string ReplyIPAddress
{
get { return dnsReplyIPaddr; }
set { dnsReplyIPaddr = value; }
}
public IPStatus PrevHostPingStatus
{
get { return prevHostPingStatus; }
set { prevHostPingStatus = value; }
}
public IPStatus CurrHostPingStatus
{
get { return currHostPingStatus; }
set
{
//prevHostPingStatus = currHostPingStatus;
currHostPingStatus = value;
}
}
public int HostReachableCount
{
get { return hostReachableCount; }
set { hostReachableCount = value; }
}
public int HostUnreachableCount
{
get { return hostUnreachableCount; }
set { hostUnreachableCount = value; }
}
// public List<DateRange> UnreachableDates {get ;private set;}
// {
// get {
// return unreachableDates;
// }
// set {
// DateRange dr = new DateRange();
// dr.Index = value.Index;
// dr.Start = value.Start;
// dr.End = value.End;
// unreachableDates.Add(dr);
// }
// }
public TimeSpan HostUnreachableTimespan
{
get { return hostUnreachableTimespan; }
set { hostUnreachableTimespan = value; }
}
public TimeSpan HostReachableTimespan
{
get { return hostReachableTimespan; }
set { hostReachableTimespan = value; }
}
public int Errorcode
{
get { return errorCode; }
set { errorCode = value; }
}
public string ErrorMsg
{
get { return errorMsg; }
set { errorMsg = value; }
}
public int CurrHostPingCount
{
get { return currHostPingCount; }
set { currHostPingCount = value; }
}
public int PrevStatusPingCount
{
get { return prevStatusPingCount; }
set { prevStatusPingCount = value; }
}
public int OptionsTtl
{
get { return optionsTtl; }
set { optionsTtl = value; }
}
public DateTime Startdate
{
get { return startDate; }
set { startDate = DateTime.Now; }
}
public DateTime Enddate
{
get { return endDate; }
set { endDate = DateTime.Now; }
}
public DateTime CurrStatusPingDatePrevious
{
get { return currStatusPingDatePrevious; }
set
{
currStatusPingDatePrevious = value;
}
}
public DateTime CurrStatusPingDateCurrent
{
get { return currStatusPingDateCurrent; }
set { currStatusPingDateCurrent = value; }
}
public DateTime PrevStatusPingDate
{
get { return prevStatusPingDate; }
set { prevStatusPingDate = value; }
}
public bool PingByIP
{
get { return pingByIP; }
set { pingByIP = value; }
}
public long RoundTrip
{
get { return pingReplyRoundTripInMiliSec; }
set { pingReplyRoundTripInMiliSec = value; }
}
public void Printout()
{
string MYFUNCTION = "Printout";
Console.WriteLine("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("[" + MYFUNCTION + "] LookupString(User Searched String) = " + LookupString);
Console.WriteLine("[" + MYFUNCTION + "] DnsResolvedHostname = " + _DnsResolvedHostname);
Console.WriteLine("[" + MYFUNCTION + "] DisplayName = " + _DisplayName);
if (IPAddress != null)
{
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr = " + IPAddress.ToString());
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr Type = " + IPAddress.AddressFamily);
}
else
{
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr = ");
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr Type = ");
}
Console.WriteLine("[" + MYFUNCTION + "] dnsReplyIPaddr = " + dnsReplyIPaddr);
Console.WriteLine("[" + MYFUNCTION + "] DnsLookupStatus = " + DnsLookupStatus);
Console.WriteLine("[" + MYFUNCTION + "] parentTarget = " + parentTarget);
Console.WriteLine("[" + MYFUNCTION + "] pingReplyRoundTripInMiliSec = " + pingReplyRoundTripInMiliSec);
Console.WriteLine("[" + MYFUNCTION + "] optionsTtl = " + optionsTtl);
Console.WriteLine("[" + MYFUNCTION + "] errorMsg = " + errorMsg);
Console.WriteLine("[" + MYFUNCTION + "] errorCode = " + errorCode);
Console.WriteLine("[" + MYFUNCTION + "] hostUnreachableCount = " + hostUnreachableCount);
Console.WriteLine("[" + MYFUNCTION + "] hostReachableCount = " + hostReachableCount);
Console.WriteLine("[" + MYFUNCTION + "] startDate = " + startDate);
Console.WriteLine("[" + MYFUNCTION + "] endDate = " + endDate);
Console.WriteLine("[" + MYFUNCTION + "] LogFile = " + logFile);
Console.WriteLine("[" + MYFUNCTION + "] DnsLookupByCodes = " + _DnsLookupType);
Console.WriteLine("[" + MYFUNCTION + "] PingByIP = " + pingByIP);
Console.WriteLine("[" + MYFUNCTION + "] Skip = " + skip);
Console.WriteLine("[" + MYFUNCTION + "] currHostPingCount = " + currHostPingCount);
Console.WriteLine("[" + MYFUNCTION + "] currHostPingStatus = " + currHostPingStatus);
Console.WriteLine("[" + MYFUNCTION + "] currStatusPingDateCurrent = " + currStatusPingDateCurrent);
Console.WriteLine("[" + MYFUNCTION + "] currStatusPingDatePrevious = " + currStatusPingDatePrevious);
Console.WriteLine("[" + MYFUNCTION + "] prevHostPingStatus = " + prevHostPingStatus);
Console.WriteLine("[" + MYFUNCTION + "] PrevStatusPingCount = " + prevStatusPingCount);
Console.WriteLine("[" + MYFUNCTION + "] prevStatusPingDate = " + prevStatusPingDate);
Console.WriteLine("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++++++++++");
}
public void Printshortnames()
{
string MYFUNCTION = "Printout-Shortnames";
Console.WriteLine("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("[" + MYFUNCTION + "] LookupString(User Searched String) = " + LookupString);
Console.WriteLine("[" + MYFUNCTION + "] DnsResolvedHostname = " + _DnsResolvedHostname);
Console.WriteLine("[" + MYFUNCTION + "] DisplayName = " + _DisplayName);
if (IPAddress != null)
{
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr = " + IPAddress.ToString());
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr Type = " + IPAddress.AddressFamily);
}
else
{
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr = ");
Console.WriteLine("[" + MYFUNCTION + "] dnsipaddr Type = ");
}
Console.WriteLine("[" + MYFUNCTION + "] dnsReplyIPaddr = " + dnsReplyIPaddr);
}
}
class Program
{
static async Task Main(string[] args)
{
string MYFUNCTION = "MAIN";
// List<Task<PingReply>> pingTasks = new List<Task<PingReply>>();
Ping pingSender = new Ping();
//List<PingerTarget> tmpHostObjectList = new List<PingerTarget>();
List<PingerTarget> listOfUserRequestedTargets = new List<PingerTarget>();
List<PingerTarget> pingableTargetList = new List<PingerTarget>();
List<DnsHostObject> listDnsHostsObjects = new List<DnsHostObject>();
Console.CancelKeyPress += delegate {
ShowSummary(pingableTargetList);
};
//List<DnsHostObject> listDnsHostsObjects;
// Create the ping target object, aka pt
//PingerTarget pt;= new PingerTarget(); // <- Review this guy
bool verbose = false; // true = print additional versbose stuff for the program
int items = -1; // compensate for "pinger" counting as 1 command line argument
//bool ENABLE_CONTINEOUS_PINGS = false; // by default use the smart ping switch
bool return_code_only = false;
string inputTargetList = ""; // target IP address or DNS name to ping
string outputCSVFilename = "";
string outstr = "";
//int sleeptimesec = Globals.SLEEP_IN_USER_REQUESTED_IN_MILLISECONDS / 1000;
double timelapsSinceStatusChange = 0; // time since the last status change
//int proposedSleepTime = Globals.SLEEP_IN_USER_REQUESTED_IN_MILLISECONDS;
// Create a buffer of 32 bytes of data to be transmitted.
//string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
// Create a buffer of 64 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeoutms = Globals.DEFAULT_TIMEOUT_MILLISECONDS;
int timeoutsec = timeoutms / 1000;
// Use the default Ttl value which is 128,
// but change the fragmentation behavior.
// iterate through the arguments
string[] arguments = Environment.GetCommandLineArgs();
for (int argIndex = 0; argIndex < arguments.Length; argIndex++)
{
//LogThis("Arguments " + arg);
switch (arguments[argIndex].ToUpper())
{
case "/?":
ShowSyntax();
Globals.RUNTIME_ERROR = ResultCodes.Error;
break;
case "-R": // Returns code only, doesn't expects a value after this switch
return_code_only = true;
Globals.PING_COUNT_VALUE_USER_SPECIFIED = 1;
Globals.MAX_COUNT_USER_SPECIFIED = true;
break;
case "-V":
Globals.PROGRAM_VERBOSE_LEVEL1 = true;
break;
case "-VV":
Globals.PROGRAM_VERBOSE_LEVEL2 = true;
break;
case "-I":
Globals.PING_ALL_IP_ADDRESSES = true;
break;
case "-S": // Make pinger like ping and output every responses to screen
Globals.ENABLE_CONTINEOUS_PINGS = true;
break;
case "-N": // No loop, same as using '-c 1'
Globals.PING_COUNT_VALUE_USER_SPECIFIED = 1;
Globals.MAX_COUNT_USER_SPECIFIED = true;
//loop = false;
break;
case "-Q": // quietens audible sounds (beeps)
Globals.SILENCE_AUDIBLE_ALARM = true;
break;
case "-F": // overrides pinger from sleeping 1 second betyween a ping response and the next ping. This will increase the ping withing a second.
Globals.FORCE_SLEEP = false;
break;
case "-C": // Specify how many times pinger will loop ping a host, expects a positive value after the switch equal or greater than 1
try
{
argIndex++; // get the next value, hopefully a digit
//bool success = int.TryParse(arguments[argIndex], out sleeptime);
Globals.MAX_COUNT_USER_SPECIFIED = true;
Globals.PING_COUNT_VALUE_USER_SPECIFIED = int.Parse(arguments[argIndex]);
}
catch (System.ArgumentNullException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.FormatException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.OverflowException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.IndexOutOfRangeException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
break;
case "-D": // Run pinger for a number of hours, expects a positive value after the switch
try
{
argIndex++; // get the next value, hopefully a digit
//bool success = int.TryParse(arguments[argIndex], out sleeptime);
Globals.DURATION_VALUE_IN_DECIMAL = double.Parse(arguments[argIndex]);
Globals.DURATION_USER_SPECIFIED = true;
// Convert numnber to timespan
Globals.DURATION_TIMESPAN = TimeSpan.FromHours(Globals.DURATION_VALUE_IN_DECIMAL);
Globals.DURATION_END_DATE = DateTime.Now.Add(Globals.DURATION_TIMESPAN);
Globals.MAX_COUNT_USER_SPECIFIED = false;
//loop = true;
}
catch (System.ArgumentNullException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.FormatException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.OverflowException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.IndexOutOfRangeException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
break;
case "-CSV": // Output each ping responses to a CSV file but matches onscreen output.
//verbose = false;
Globals.OUTPUT_SCREEN_TO_CSV = true;
Globals.OUTPUT_ALL_TO_CSV = !Globals.OUTPUT_SCREEN_TO_CSV;
break;
case "-CSVALL": // Output each ping responses to a CSV file even if you are using the ENABLE_CONTINEOUS_PINGS function
//verbose = false;
Globals.OUTPUT_SCREEN_TO_CSV = false;
Globals.OUTPUT_ALL_TO_CSV = !Globals.OUTPUT_SCREEN_TO_CSV;
break;
case "-P": // Poll every 'n' seconds, expects a value after this switch
try
{
argIndex++; // get the next value, hopefully a digit
//bool success = int.TryParse(arguments[argIndex], out sleeptime);
Globals.SLEEP_IN_USER_REQUESTED_IN_SECONDS = int.Parse(arguments[argIndex]);
Globals.SLEEP_IN_USER_REQUESTED_IN_MILLISECONDS = Globals.SLEEP_IN_USER_REQUESTED_IN_SECONDS * 1000;
}
catch (System.ArgumentNullException)
{
LogThis("Please specify a valid polling interval in seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.FormatException)
{
LogThis("Please specify a valid polling interval in seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.OverflowException)
{
LogThis("Please specify a valid polling interval in seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.IndexOutOfRangeException)
{
LogThis("Please specify a valid polling interval in seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
break;
case "-SKIPDNSLOOKUP": // skip DNS lookups
Globals.SKIP_DNS_LOOKUP = true;
break;
case "-DNSONLY": // skip DNS lookups
Globals.PING_ONLY_DNS_RESOLVABLE_TARGETS = true;
break;
case "-DNSSERVER": // skip DNS lookups
try
{
argIndex++; // get the next value, hopefully a digit
Globals.DNS_SERVER = arguments[argIndex];
}
catch (System.ArgumentNullException)
{
LogThis("Please specify a valid number.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
break;
case "-T": // smart switch
// Show OK and Down and OK, implies -C
try
{
argIndex++; // get the next value, hopefully a digit
timeoutsec = int.Parse(arguments[argIndex]);
if (timeoutsec == 0)
{
timeoutsec = 1;
}
timeoutms = timeoutsec * 1000; // convert to millisecomnds
}
catch (System.ArgumentNullException)
{
LogThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.FormatException)
{
LogThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.OverflowException)
{
LogThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
catch (System.IndexOutOfRangeException)
{
LogThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
break;
case "-IPV4": // ipv4 IP Addresses only
Globals.IPV4_ONLY_IF = true;
break;
case "-IPV6": // ipv4 IP Addresses only
Globals.IPV6_ONLY_IF = true;
break;
default:
if (items == 0)
{
inputTargetList = arguments[argIndex];
Globals.ENABLE_CONTINEOUS_PINGS = false;
}
items++;
break;
}
}
//if (Globals.RUNTIME_ERROR != ResultCodes.Ok)
//return 1;//Globals.RUNTIME_ERROR;
if (items > 1 || inputTargetList.Length <= 0)
{
ShowSyntax();
Globals.RUNTIME_ERROR = ResultCodes.Error;
}
else
{
/*
* Show GLobal Variables
*/
//PrintOutGlobalVariables();
/*
* STEP 1: BUILD UP THE LIST OF SYSTEMS SPECIFIED BY USER
*/
// Determine the list of hosts to ping
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
LogThisVerbose("[" + MYFUNCTION + "] STEP 1: DNS Lookup user host list ");
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
string[] arrTargets;
List<string> inputTargetListFiltered = new List<string>(); ; // need to work out why this is there.
foreach (string targetHostname in inputTargetList.Split(','))
{
inputTargetListFiltered.Add(targetHostname);
}
arrTargets = inputTargetListFiltered.Distinct().ToArray();
if (Globals.PROGRAM_VERBOSE_LEVEL2)
{
//LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++++++++++++++++ ");
LogThisVerbose("[" + MYFUNCTION + "] User specified Targets:");
foreach (string str in arrTargets)
{
LogThisVerbose("[" + MYFUNCTION + "] : " + str);
}
}
if (Globals.IPV4_ONLY_IF)
{
LogThisVerbose("[" + MYFUNCTION + "] User Requested pinger on IPv4 Records only");
}
if (Globals.IPV6_ONLY_IF)
{
LogThisVerbose("[" + MYFUNCTION + "] User Requested pinger on IPv6 Records only");
}
/*
* STEP 2: ITERATE and ATTEMPT TO DNS Lookup all. Process the results.
* Ignore hostnames that do not have IP addresses resolvable
* If the user specifies for IPV4 only, then filter out non-IPv4 addresses
* bad hostname lookups and ipv6
* Output an array of DnsHostObjects for processing into a pinger target list
* Note the the
*/
// The list of final dns records for processing
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
LogThisVerbose("[" + MYFUNCTION + "] STEP 2: Filtering DnsHostObjects ");
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
string subFunction = "Foreach";
// Iterate through the targets by 1 DNS lookup, and 2 add finalise list into listDnsHostsObjects
int arrTargetsIndex = 0;
int dnsRecordsIndex = 0;
foreach (string hostname in arrTargets)
{
DateTime startTime = DateTime.Now;
//LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++++++++++++++++ ");
LogThisVerbose("[" + MYFUNCTION + "] Looking up [ " + hostname + " ] ");
// What if we 1) Attempt to resolve, 2) if you can't just ping by IP
// For each target, check if we need to do a DNS lookup first - -Globals.SKIP_DNS_LOOKUP is enabled or node
if (Globals.SKIP_DNS_LOOKUP == false)
{
// User wants to perform a DNS lookup using the system DNS server
//string[] dnsresults = DnsLookup(hostname);
subFunction = "DnsLookup";
DnsHostObject hostLookupResults = DnsLookupNew(hostname);
hostLookupResults.LookupString = hostname;
if (Globals.PROGRAM_VERBOSE_LEVEL2)
{
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Calling hostLookupResults.Printout()");
//LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] ++++++++++++++++++++++++++++++++++++");
hostLookupResults.Printout();
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] ++++++++++++++++++++++++++++++++++++");
}
/*
ITERATE THROUGH THE LIST OF DnsHostObjects to use as input for pinger's list
*/
subFunction = "Filtering Records";
if (
(hostLookupResults.DnsLookUpCode == ResultCodes.Ok) ||
(
(hostLookupResults.DnsLookupType == DnsLookupByCodes.ByIP) &&
(hostLookupResults.DnsLookUpCode == ResultCodes.Error) &&
!Globals.PING_ONLY_DNS_RESOLVABLE_TARGETS
)
)
{
// This means that the Resolution (Forward or reverse were successfull)
// Iterate through the <ibvj>.IPAddresses
// Filter IPV4 if requested, and finalise the list
//LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Returned IP [" + ipIndex + "] = " + ip.ToString() + "][" + ip.AddressFamily + "]");
int recordIndex = 0;
bool tryagain = true; // If you need the 1st IP of IPV4 or IPV6, but DNS returns the opposite, you want to continue until you find a match
foreach (System.Net.IPAddress addr in hostLookupResults.IPAddresses)
{
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Exporting IP addresses for " + hostLookupResults.LookupString);;
DnsHostObject tmpDnsHostsObject = new DnsHostObject(hostLookupResults.LookupString);
tmpDnsHostsObject.DnsResolvedHostname = hostLookupResults.DnsResolvedHostname;
tmpDnsHostsObject.DnsLookUpMessage = hostLookupResults.DnsLookUpMessage;
tmpDnsHostsObject.DnsLookUpCode = hostLookupResults.DnsLookUpCode;
tmpDnsHostsObject.DnsLookupType = hostLookupResults.DnsLookupType;
tmpDnsHostsObject.Index = dnsRecordsIndex;
tmpDnsHostsObject.IPAddresses = new System.Net.IPAddress[] { addr };
// By default include it in the list unless there is a reason not to
tmpDnsHostsObject.Skip = false;
//if (Globals.IPV4_ONLY_IF || Globals.IPV6_ONLY_IF)
//{
if ((Globals.IPV4_ONLY_IF && (addr.AddressFamily != AddressFamily.InterNetwork)))
{
//LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Excluding Record [" + hostLookupResults.LookupString + " if=" + recordIndex + " [" + addr.ToString() + "/" + addr.AddressFamily + "]");
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Excluding Record - Want IPv4 instead have if=" + recordIndex + " [" + addr.ToString() + "/" + addr.AddressFamily + "]");
tmpDnsHostsObject.Skip = true;
tryagain = true;
}
else if ((Globals.IPV6_ONLY_IF && (addr.AddressFamily != AddressFamily.InterNetworkV6)))
{
//LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Including IPv6 Record [" + hostLookupResults.LookupString + " if=" + recordIndex + " [" + addr.ToString() + "/" + addr.AddressFamily + "]");
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Excluding Record - Want IPv6 instead have if=" + recordIndex + " [" + addr.ToString() + "/" + addr.AddressFamily + "]");
tmpDnsHostsObject.Skip = true;
tryagain = true;
}
else
{
// We don't get which interface we are grabbing first. Which ever DNS resolve reports back first.
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Including Record [" + addr.ToString() + "]");
hostLookupResults.Skip = false;
tryagain = false;
}
// If the ip address is 0.0.0.0 or ::0, ignore it
if ( (addr.ToString() == "0.0.0.0") || (addr.ToString() == "::0"))
{
tmpDnsHostsObject.Skip = true;
LogThisVerbose ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
LogThisVerbose ("IP address = " + addr.ToString());
LogThisVerbose ("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
}
//
if (tryagain == false)
{
listDnsHostsObjects.Add(tmpDnsHostsObject);
}
if (!Globals.PING_ALL_IP_ADDRESSES && tryagain == false)
{
// When user choses Globals.PING_ALL_IP_ADDRESSES=true, we find the 1st interface only. otherwise we grab all DNS IP addresses
break;
}
dnsRecordsIndex++;
recordIndex++;
}
}
else // if ((hostLookupResults.DnsLookUpCode == ResultCodes.Error) && (hostLookupResults.DnsLookupType == DnsLookupByCodes.ByName))
{
hostLookupResults.Skip = true;
hostLookupResults.Index = dnsRecordsIndex;
listDnsHostsObjects.Add(hostLookupResults);
// This means that the user requested the lookup of an Name AND DNS resolution failed, we skip it
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "][Catch all] Record Will Skipped [" + hostLookupResults.LookupString + "]");
dnsRecordsIndex++;
}
}
else
{
// User requested to skip DNS lookups
DnsHostObject tmpDnsHostsObject = new DnsHostObject(hostname);
tmpDnsHostsObject.LookupString = hostname;
tmpDnsHostsObject.DnsLookUpCode = ResultCodes.Error;
tmpDnsHostsObject.DnsLookUpMessage = "DNS resolution skipped";
tmpDnsHostsObject.Index = dnsRecordsIndex;
tmpDnsHostsObject.Skip = false;
listDnsHostsObjects.Add(tmpDnsHostsObject);
dnsRecordsIndex++;
}
arrTargetsIndex++;
} /// End foreach hostnames
/*
* STEP 3: Process the list of listDnsHostsObjects and convert into a anrray of ping targets that pinger can process
*/
// all the records can be processed without filtering
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
LogThisVerbose("[" + MYFUNCTION + "] STEP 3: Generating PingerTarget arrays");
LogThisVerbose("[" + MYFUNCTION + "] ++++++++++++++++++++++++++++++++++++");
subFunction = "PingTargetList";
string previousLookupString = "";
int interfaceIndexDefaultStart = 0;
int interfaceIndex = interfaceIndexDefaultStart;
int recordsIndex = 0;
// Expecting listDnsHostsObjects to be ordered by LookupString
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Generating Pinger Target list from " + listDnsHostsObjects.Count + " objects");
foreach (DnsHostObject dnsRecord in listDnsHostsObjects)//.OrderBy(q => q.LookupString).ToList())
{
subFunction = "foreach";
PingerTarget currentHostInterface = new PingerTarget(dnsRecord.LookupString, dnsRecord.Index);
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Object " + recordsIndex + ": " + dnsRecord.LookupString);
// Find if there are duplicates that we need to be ware off
if (dnsRecord.DnsLookUpCode == ResultCodes.Ok)
{
if (dnsRecord.DnsResolvedHostname != null)
{
currentHostInterface.DisplayName = dnsRecord.DnsResolvedHostname;
}
if (dnsRecord.IPAddresses != null)
{
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] IP: " + dnsRecord.IPAddresses[0].ToString());
}
}
else
{
currentHostInterface.DisplayName = dnsRecord.LookupString;
}
if (previousLookupString == dnsRecord.LookupString)
{
// The record.LookupString has multiple IPs to ping, therefore up the interface Index number for visual display
interfaceIndex++;
currentHostInterface.DisplayName += "-IP-" + interfaceIndex;
}
currentHostInterface.Skip = dnsRecord.Skip;
currentHostInterface.DnsLookupStatus = dnsRecord.DnsLookUpCode;
currentHostInterface.DnsLookupMessage = dnsRecord.DnsLookUpMessage;
if (dnsRecord.DnsResolvedHostname != null)
{
currentHostInterface.DnsResolvedHostname = dnsRecord.DnsResolvedHostname;
}
//dnsRecord.Printout();
if (dnsRecord.IPAddresses != null)
{
LogThisVerbose(">>> There is an IP");
currentHostInterface.IPAddress = dnsRecord.IPAddresses[0];
}
else
{
LogThisVerbose(">>> There is NO IP");
}
LogThisVerbose(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
/*if (record.DnsResolvedHostname != null)
{
currentHostInterface.DnsResolvedHostname = record.DnsResolvedHostname;
currentHostInterface.DisplayName = displayName;
}
currentHostInterface.IPAddress = record.IPAddresses[0];
currentHostInterface.Skip = record.Skip;
*/
if (Globals.PROGRAM_VERBOSE_LEVEL2)
{
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] START ________________________________________");
currentHostInterface.Printout();
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] END ________________________________________");
}
//
if (currentHostInterface != null)
{
// if listOfUserRequestedTargets does not already contains an entry with the same Displayname, then add it
PingerTarget result = listOfUserRequestedTargets.Find(x => x.DisplayName == currentHostInterface.DisplayName);
if (result == null)
{
LogThisVerbose("[" + MYFUNCTION + "][" + subFunction + "] Adding " + currentHostInterface.DisplayName + " to listOfUserRequestedTargets");