Tools - TcpIp.cs
42.9 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Linq;
namespace Vrh.Log4Pro.MaintenanceConsole.ToolsNS
{
/// <summary>
/// A pinger objektum ping ciklusokat indít (egy ping ciklusban több ping kérés van/lehet), és ezek eredményét
/// tárolja tömörített formátumban elsősorban abból a célból, hogy a tárolt adatok alapján trend diagramot lehessen
/// készíteni a kapcsolat minőségének kimutatására.
/// </summary>
public class Pinger : IDisposable
{
/// <summary>
/// Egy Pinger objektum létrehozása xml-ből
/// </summary>
/// <param name="hostNameOrAddress">a ping célállomása</param>
/// <param name="pingerconfig">a pinger konfigurációs paramétereit tartalmazó xml struktúra</param>
public Pinger(string hostNameOrAddress, XElement pingerconfig) : this(hostNameOrAddress, new PingerConfig(pingerconfig)) { }
/// <summary>
/// Egy Pinger objektum létrehozása PrinterConfig osztályból
/// </summary>
/// <param name="hostNameOrAddress">a ping célállomása</param>
/// <param name="pc">a konfigurációt tartalmazó pinger objektum</param>
private Pinger(string hostNameOrAddress, PingerConfig pc)
{
this.HostNameOrAddress = hostNameOrAddress;
this.History = new PingHistory(hostNameOrAddress, pc);
this.PingTimeout = pc.pingtimeout;
this.PingCycleFrequency = pc.pingcyclefrequency;
this.PingCycleNumberOfPackages = pc.pingcyclenumofpackages;
this.PingerActiveLength = pc.pingeractivlength;
this.Configuration = pc;
if (pc.RoundTripTimeLimits!=null)
{
Pinger.RoundTripTimeLimits = pc.RoundTripTimeLimits;
Pinger.MaxRoundTripTimeoutCategory = pc.RoundTripTimeLimits.Last();
Pinger.RoundTripTimeyCategoryLimits = pc.RoundTripTimeyCategoryLimits;
}
}
/// <summary>
/// A maximális ping timeout kategória értéke
/// </summary>
public static int MaxRoundTripTimeoutCategory = 5000;
/// <summary>
/// A FINOM válaszidő kategóriákat tartalmazza; egy válasz az i. válaszidő kategóriába tartozik, ha a pontos válaszidő nagyobb, vagy egyenlő,
/// mint az i. elem értéke, de kisebb, mint az i+1. elem értéke.A sor első elemének értéke mindig 0!!!!
/// Ha a sor értékei: 0:0,1:100,2:200,3:300,4:400,5:500, a pontos válaszidő 350, akkor ez a 2. kategóriába tartozik, ha pontos válaszidő.
/// </summary>
public static List<int> RoundTripTimeLimits = new List<int> { 0, 25, 50, 75, 100, 150, 200, 250, 300, 400, 500, 750, 1000, 1250, 1500, 1750, 2000, 2500, 3000, 3500, 4000, 4500, Pinger.MaxRoundTripTimeoutCategory, };
/// <summary>
/// A DURVA válaszidő kategóriákat tartalmazza; egy válasz az i. válaszidő kategóriába tartozik, ha a pontos válaszidő nagyobb, vagy egyenlő,
/// mint az i. elem értéke, de kisebb, mint az i+1. elem értéke.A sor első elemének értéke mindig 0!!!!
/// Ha a sor értékei: 0:0,1:100,2:200,3:300,4:400,5:500, a pontos válaszidő 350, akkor ez a 2. kategóriába tartozik, ha pontos válaszidő.
/// </summary>
public static List<int> RoundTripTimeyCategoryLimits = new List<int> { 0, 50, 250, 750, };
/// <summary>
/// A pinger indítása/újraindítása; elindítja a ping ciklus időzítőt, és elkezdi/folytatja a ping státusz adatok letárolását
/// </summary>
/// <param name="pingerconfig">pinger konfig xml struktúra, amely
/// (jellemzően újraindítás esetén) a Pinger részleges átkonfigurálását teszi lehetővé</param>
public void Start(XElement pingerconfig = null)
{
lock (pingcyclelocker)
{
CycleTimerStop();
Reconfigure(pingerconfig);
CycleTimerStart();
if (this.PingerActiveLength > 0)
{
AutoStopTimerStop();
AutoStopTimerStart();
}
}
}
/// <summary>
/// A pinger leállítása; kikapcsolja a ping ciklus időzítőt, és leállítja a ping státusz adatok letárolását
/// </summary>
public void Stop()
{
CycleTimerStop();
}
/// <summary>
/// A Pinge objektum átkonfigurálás a a megadott xml struktúra alapján
/// </summary>
/// <param name="pingerconfig"></param>
private void Reconfigure(XElement pingerconfig = null)
{
lock (pingcyclelocker)
{
if (pingerconfig != null)
{
var pc = new PingerConfig(pingerconfig);
this.PingTimeout = pc.pingtimeout;
this.PingCycleFrequency = pc.pingcyclefrequency;
this.PingCycleNumberOfPackages = pc.pingcyclenumofpackages;
this.PingerActiveLength = pc.pingeractivlength;
this.History.SetHistoryLength(pc.pingerhistorylength);
if (pc.RoundTripTimeLimits != null)
{
Pinger.RoundTripTimeLimits = pc.RoundTripTimeLimits;
Pinger.MaxRoundTripTimeoutCategory = pc.RoundTripTimeLimits.Last();
Pinger.RoundTripTimeyCategoryLimits = pc.RoundTripTimeyCategoryLimits;
}
}
}
}
/// <summary>
/// A pinger autostop lejártakor végrehajtandó metódus
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void AutoStop(Object source, ElapsedEventArgs e) { CycleTimerStop(); }
private void CycleTimerStop()
{
lock (pingcyclelocker) { if (this.CycleTimer != null) { this.CycleTimer.Enabled = false; } this.Operating = false; }
}
private void CycleTimerStart()
{
lock (pingcyclelocker)
{
if (this.CycleTimer == null) { this.CycleTimer = new System.Timers.Timer(); this.CycleTimer.Elapsed += StartPingCycle; this.CycleTimer.AutoReset = true; }
this.CycleTimer.Interval = this.PingCycleFrequency;
this.CycleTimer.Enabled = true;
this.Operating = true;
}
}
private void AutoStopTimerStop()
{
lock (pingcyclelocker)
{
if (this.AutoStopTimer != null) { this.AutoStopTimer.Enabled = false; }
}
}
private void AutoStopTimerStart()
{
lock (pingcyclelocker)
{
if (this.AutoStopTimer == null) { this.AutoStopTimer = new System.Timers.Timer(); this.AutoStopTimer.Elapsed += AutoStop; this.AutoStopTimer.AutoReset = false; }
this.AutoStopTimer.Interval = this.PingerActiveLength;
this.AutoStopTimer.Enabled = true;
}
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
Stop();
if (this.CycleTimer != null) { this.CycleTimer.Dispose(); this.CycleTimer = null; }
if (this.AutoStopTimer != null) { this.AutoStopTimer.Dispose(); this.AutoStopTimer = null; }
this.History.Dispose();
}
/// <summary>
/// Visszadja a history listát
/// </summary>
/// <returns></returns>
public Pinger.PingHistory GetHistory()
{
lock (pingcyclelocker) { this.History.PingerState = this.CycleTimer != null && this.CycleTimer.Enabled ? PingerStatus.Operating : PingerStatus.Still; return this.History; }
}
#region public fields
/// <summary>
/// A ping célállomása
/// </summary>
public string HostNameOrAddress;
/// <summary>
/// true: a pingcycle timer működik, a pingelés folyamataos
/// false: a pingcycle timer NEM működik, a pingelés áll
/// </summary>
public bool Operating;
/// <summary>
/// Egy ciklusban kiadott ping kérések száma.
/// </summary>
public PingerConfig Configuration;
#endregion public fields
#region private metódusok
/// <summary>
/// A ping ciklus időzítés lejártakor elindított metódus, ami végrehajt egy ping ciklust és eredményét bedolgozza a PingStateQueue sorba
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
private void StartPingCycle(Object source, ElapsedEventArgs e)
{
lock (pingcyclelocker)
{
this.CycleTimer.Enabled = false; // kikapcsoljuk a timer-t a ciklus végrehajtása alatt
var newpc = new PingCycle(this.HostNameOrAddress, this.PingCycleNumberOfPackages, this.PingTimeout).Execute();
this.History.Merge(newpc);
this.CycleTimer.Interval = this.PingCycleFrequency;// ha esetleg közben újrakonfigurálták....
this.CycleTimer.Enabled = true; // a ciklus végrehajtása után ismét elindítjuk az időzítőt
}
}
#endregion private metódusok
#region private fields
/// <summary>
/// Az egyes ping kérések maximális timeout-ja (millisecundum)
/// </summary>
private int PingTimeout;
/// <summary>
/// A ping ciklus befejeződése után ennyi idővel indítja a következőt (másodpercben)
/// </summary>
private int PingCycleFrequency;
/// <summary>
/// A ping vizsgálat teljes időtartama; Ennyi idő eltelte után nem indít több több ping ciklust.
/// Érték percben. Ha az érték 0, akkor végtelen hosszú időn keresztül indít ping ciklusokat.
/// </summary>
private int PingerActiveLength;
/// <summary>
/// Egy ciklusban kiadott ping kérések száma.
/// </summary>
private int PingCycleNumberOfPackages;
/// <summary>
/// A ping ciklusok keveredését megakadályozó locker objektum
/// </summary>
private object pingcyclelocker = new object();
/// <summary>
/// A Pinger működési periódusának hossza (az autostop timer kikapcsolási ideje) (perc)
/// </summary>
private System.Timers.Timer AutoStopTimer;
/// <summary>
/// A Ping ciklus timere
/// </summary>
private System.Timers.Timer CycleTimer;
/// <summary>
/// Ping history
/// </summary>
private PingHistory History;
#endregion private fields
#region PingerConfig class
/// <summary>
/// PingerConfig osztály
/// </summary>
public class PingerConfig
{
/// <summary>
/// példány létrehozása xml struktúra alapján
/// </summary>
/// <param name="pingerconfig"></param>
public PingerConfig(XElement pingerconfig)
{
if (pingerconfig != null)
{
var _pingtimeout = GetPositiveIntFromXml(PINGTIMEOUT, pingerconfig);
var _pingcyclefrequency = GetPositiveIntFromXml(PINGCYCLEFREQUENCY, pingerconfig);
var _pingcyclenumofpackages = GetPositiveIntFromXml(PINGCYCLENUMOFPACKAGES, pingerconfig);
var _pingerlifetime = GetPositiveIntFromXml(PINGERACTIVELENGTHTOSTOPPERIOD, pingerconfig);
var _pingerhistorylength = GetPositiveIntFromXml(PINGERHISTORYLENGTH, pingerconfig);
var _optimizehistorylength = pingerconfig.Element(OPTIMIZEHISTORYLENGTH)?.Value; ;
var _roundtriptimelimits = pingerconfig.Element(ROUNDTRIPTIMELIMITS)?.Value;
var _roundtriptimecategorylimits = pingerconfig.Element(ROUNDTRIPTIMECATEGORYLIMITS)?.Value;
SetValues(_pingtimeout, _pingcyclefrequency, _pingcyclenumofpackages, _pingerlifetime, _pingerhistorylength, _roundtriptimelimits, _roundtriptimecategorylimits,_optimizehistorylength);
}
else { SetValues(); }
}
/// <summary>
/// Példány létrehozása paraméterek alapján; a konstruktor célja a mértékegységek és a default értékek kezelése
/// </summary>
/// <param name="pingtimeout">millisecond</param>
/// <param name="pingcyclefrequency">seconds</param>
/// <param name="pingcyclenumofpackages">pcs</param>
/// <param name="pingeractivelength">minutes</param>
/// <param name="pingerhistorylength">minutes</param>
public PingerConfig(int pingtimeout = 0, int pingcyclefrequency = 0, int pingcyclenumofpackages = 0, int pingeractivelength = 0, int pingerhistorylength = 0,string rttlimits=null, string rttcatlimits=null,string optimizehlength=null)
{
SetValues(pingtimeout, pingcyclefrequency, pingcyclenumofpackages, pingeractivelength, pingerhistorylength, rttlimits , rttcatlimits, optimizehlength);
}
/// <summary>
/// Beállítja a field-ek értékét a megfelelő mértékegységben a paraméterek, illetve az alapértelmezések szerint
/// </summary>
/// <param name="pingtimeout">millisecond</param>
/// <param name="pingcyclefrequency">seconds</param>
/// <param name="pingcyclenumofpackages">pcs</param>
/// <param name="pingeractivelength">minutes</param>
/// <param name="pingerhistorylength">minutes</param>
private void SetValues(int pingtimeout = 0, int pingcyclefrequency = 0, int pingcyclenumofpackages = 0, int pingeractivelength = 0, int pingerhistorylength = 0, string rttlimits = null, string rttcatlimits = null,string optimizehlength=null)
{
this.pingcyclenumofpackages = pingcyclenumofpackages <= 0 ? PingerConfig.DEFAULT_PINGCYCLENUMOFPACKAGES : pingcyclenumofpackages;
this.pingeractivlength = (pingeractivelength <= 0 ? PingerConfig.DEFAULT_PINGERACTIVELENGTH : pingeractivelength) * 60 * 1000;
this.pingerhistorylength = (pingerhistorylength <= 0 ? PingerConfig.DEFAULT_PINGERHISTORYLENGTH : pingerhistorylength) * 60 * 1000;
bool optimizehlengthbool=true;
if (optimizehlength != null) { optimizehlengthbool = bool.TryParse(optimizehlength.ToLower(), out optimizehlengthbool) ? optimizehlengthbool : true; }
this.optimizehistorylength = optimizehlengthbool;
try
{
// ha a megadott sor nem ok, akkor nem változtat a default-on
List<int> rttl = rttlimits.Split(new char[] { ' ', ',', ';', '/', }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => int.Parse(x)).ToList();
if (rttl.Count <4) { throw new Exception(); }
if (rttl.ElementAt(0) != 0) { throw new Exception(); }
int lastelementvalue = -1;
for(var i=0;i<rttl.Count;i++) { if (rttl.ElementAt(i) <= lastelementvalue) { throw new Exception(); } lastelementvalue=rttl.ElementAt(i); }
List<int> rttcl = rttcatlimits.Split(new char[] { ' ', ',', ';', '/', }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => int.Parse(x)).ToList();
if (rttcl.Count != 4) { throw new Exception(); }
if (rttcl.ElementAt(0) != 0) { throw new Exception(); }
lastelementvalue = -1;
for (var i = 0; i < rttcl.Count; i++) { if (rttcl.ElementAt(i) <= lastelementvalue) { throw new Exception(); } lastelementvalue = rttcl.ElementAt(i); }
this.RoundTripTimeLimits = rttl;
this.RoundTripTimeyCategoryLimits = rttcl;
}
catch
{
this.RoundTripTimeLimits = Pinger.RoundTripTimeLimits;
this.RoundTripTimeyCategoryLimits = Pinger.RoundTripTimeyCategoryLimits;
}
this.pingtimeout = pingtimeout <= 0 ? rttlimits.Last() : pingtimeout;
this.pingcyclefrequency = pingcyclefrequency * 1000;
if (this.pingcyclefrequency < this.pingtimeout) { this.pingcyclefrequency = this.pingtimeout; }
}
/// <summary>
/// Egy int értéket kiemel a megadott xml struktúrából, ha nincs ott a keresett érték,
/// vagy nem integer, vagy nem pozitív, akkor az alapértelmezést adja vissza
/// </summary>
/// <param name="xname">az xml struktúrában a keresett elem neve</param>
/// <param name="pingerconfig">az xml struktúra</param>
/// <param name="defaultvalue">az alapértelmezett érték</param>
/// <returns></returns>
private static int GetPositiveIntFromXml(string xname, XElement pingerconfig, int defaultvalue=0)
{
string valstr = pingerconfig?.Element(XName.Get(xname))?.Value;
int val = defaultvalue;
if (valstr != null && int.TryParse(valstr, out int val1) && val1 > 0) { val = val1; }
return val;
}
public List<int> RoundTripTimeLimits=null;
public List<int> RoundTripTimeyCategoryLimits=null;
public int pingtimeout;
public int pingcyclefrequency;
public int pingcyclenumofpackages;
public int pingeractivlength;
public int pingerhistorylength;
public bool optimizehistorylength;
const string PINGTIMEOUT = "PingTimeout";
const string PINGCYCLEFREQUENCY = "PingCycleFrequency";
const string PINGCYCLENUMOFPACKAGES = "PingCycleNumOfPackages";
const string PINGERACTIVELENGTHTOSTOPPERIOD = "PingerActiveLength";
const string PINGERHISTORYLENGTH = "PingerHistoryLength";
const string OPTIMIZEHISTORYLENGTH = "OptimizeHistoryLength";
const string ROUNDTRIPTIMELIMITS = "RoundTripTimeLimits";
const string ROUNDTRIPTIMECATEGORYLIMITS = "RoundTripCategoryLimits";
public const int DEFAULT_PINGTIMEOUT = 0;
public const int DEFAULT_PINGCYCLENUMOFPACKAGES = 4;
public const int DEFAULT_PINGERACTIVELENGTH = 60;
public const int DEFAULT_PINGERHISTORYLENGTH = 60;
}
#endregion PingerConfig class
#region PingHistory class
/// <summary>
/// Ping history struktúra
/// </summary>
public class PingHistory : IDisposable
{
/// <summary>
/// Ping állapot-sor. Minden eleme egy kezdő-időponttól fogva a következő elem kezdőidopontjáig fennálló állapotot ír le.
/// Ha az új státusz állapot-ban a RoundtripTimeCategory vagy StatusCategory értéke a sorban levő legutolsó elemben levő értékekhez képes
/// KÜLÖNBÖZIK, akkor Új elem kerül be a sorba;
/// AZONOS, akkor a legutolsó elemben a PackagesSent és PackagesLost értékekhez hozzáadódik az új elemben levő megfelelő érték, de új elem nem kerül hozzáadásra
/// </summary>
public List<PingCycle> PingStateQueue;
/// <summary>
/// A PingStateQueue utolsó eleme
/// </summary>
private PingCycle LastPingCycle;
/// <summary>
/// A tárolt history hossza percben
/// </summary>
public int Length;
/// <summary>
/// A ping ciklusok gyakorisága
/// </summary>
public int PingCycleFrequency;
/// <summary>
/// Az érvényes configuráció
/// </summary>
public PingerConfig PingerConfig;
public string HostNameOrAddress;
public PingerStatus PingerState = PingerStatus.Still;
public DateTime StartTime;
private object historylocker = new object();
public PingHistory(string hostnameoraddress, PingerConfig pingerconfig)
{
this.HostNameOrAddress = hostnameoraddress;
this.PingStateQueue = new List<PingCycle>();
this.LastPingCycle = null;
this.Length = pingerconfig.pingerhistorylength;
this.PingCycleFrequency = pingerconfig.pingcyclefrequency;
this.PingerConfig = pingerconfig;
}
public PingHistory(PingHistory ph)
{
this.HostNameOrAddress = ph.HostNameOrAddress;
this.PingStateQueue = ph.PingStateQueue.Select(x=>new PingCycle(x)).ToList();
this.LastPingCycle = ph.LastPingCycle;
this.Length = ph.Length;
this.PingCycleFrequency = ph.PingCycleFrequency;
this.PingerConfig = ph.PingerConfig;
}
public void Dispose()
{
this.PingStateQueue = null;
this.LastPingCycle = null;
}
/// <summary>
/// A PrintCycle beillesztése a sor végére, vagy "hozzáadása" az utolsó elemhez
/// </summary>
/// <param name="newpc"></param>
public void Merge(PingCycle newpc)
{
lock (historylocker)
{
if (!this.PingerConfig.optimizehistorylength || (this.LastPingCycle?.isDifferent(newpc) ?? true)) { this.PingStateQueue.Add(newpc); this.LastPingCycle = newpc; }
else
{
var totalrtt = ((this.LastPingCycle.RoundtripTimeAverage * this.LastPingCycle.NumberOfCycles) + newpc.RoundtripTimeAverage);
this.LastPingCycle.NumberOfCycles++;
this.LastPingCycle.RoundtripTimeAverage = totalrtt / this.LastPingCycle.NumberOfCycles;
this.LastPingCycle.PackagesSent += newpc.PackagesSent;
this.LastPingCycle.PackagesLost += newpc.PackagesLost;
this.LastPingCycle.PackagesSentCategory = this.LastPingCycle.GetLostPackageCategory();
this.LastPingCycle.LastTimestamp = newpc.StartTimestamp;
if (newpc.RoundtripTimeMax != -1 && this.LastPingCycle.RoundtripTimeMax != -1)
{
if (this.LastPingCycle.RoundtripTimeMax < newpc.RoundtripTimeMax) { this.LastPingCycle.RoundtripTimeMax = newpc.RoundtripTimeMax; }
if (this.LastPingCycle.RoundtripTimeMin > newpc.RoundtripTimeMin) { this.LastPingCycle.RoundtripTimeMin = newpc.RoundtripTimeMin; }
}
}
var borderts = newpc.StartTimestamp.AddMilliseconds(-1 * this.Length);
this.PingStateQueue.RemoveAll(x => x.LastTimestamp <= borderts);
var firstelement = this.PingStateQueue.FirstOrDefault();
if (firstelement != null && firstelement.StartTimestamp < borderts)
{
var partiallength = (firstelement.LastTimestamp - borderts).TotalMilliseconds;
var fulllength = (firstelement.LastTimestamp - firstelement.StartTimestamp).TotalMilliseconds;
firstelement.PackagesSent = (int)((double)firstelement.PackagesSent * partiallength / fulllength);
firstelement.PackagesLost = (int)((double)firstelement.PackagesLost * partiallength / fulllength);
firstelement.NumberOfCycles = (int)((double)firstelement.NumberOfCycles * partiallength / fulllength);
if (firstelement.NumberOfCycles == 0 || firstelement.PackagesSent == 0) { this.PingStateQueue.Remove(firstelement); firstelement = this.PingStateQueue.FirstOrDefault(); }
firstelement.PackagesSentCategory = firstelement.GetLostPackageCategory();
firstelement.StartTimestamp = borderts;
}
StartTime = firstelement?.StartTimestamp ?? DateTime.MaxValue;
}
}
/// <summary>
/// Beállítja a history hosszát
/// </summary>
/// <param name="pingerhistoryperiod"></param>
public void SetHistoryLength(int pingerhistoryperiod)
{
lock (historylocker) { this.Length = pingerhistoryperiod; }
}
}
#endregion PingHistory class
#region PingCycle class
/// <summary>
/// A ping history-ban szereplő elemek típusa
/// </summary>
public class PingCycle
{
/// <summary>
/// Ping ciklus objektum létrehozása
/// </summary>
/// <param name="hostnameoraddress">a pingek célja</param>
/// <param name="numofpings">ennyi ping-et kell végrehajtani</param>
/// <param name="pingtimeout">ennyi az egyes ping-ek timeout-ja</param>
public PingCycle(string hostnameoraddress, int numofpings, int pingtimeout)
{
this.HostNameOrAddress = hostnameoraddress;
this.PackagesSent = numofpings;
this.PingTimeout = pingtimeout;
this.PackagesLost = 0;
this.PackagesSentCategory = LostPackageCategory.Excellent;
this.NumberOfCycles = 1;
this.StatusCategory = IPStatusCategory.NotExecuted;
this.RoundtripTimeAverage = 0;
this.RoundtripTimeMin = -1;
this.RoundtripTimeMax = -1;
}
public PingCycle(PingCycle pc)
{
this.HostNameOrAddress = pc.HostNameOrAddress;
this.PackagesSent = pc.PackagesSent;
this.PingTimeout = pc.PingTimeout;
this.PackagesLost = pc.PackagesLost;
this.PackagesSentCategory = pc.PackagesSentCategory;
this.NumberOfCycles = pc.NumberOfCycles;
this.StatusCategory = pc.StatusCategory;
this.RoundtripTime = pc.RoundtripTime;
this.RoundtripTimeAverage = pc.RoundtripTimeAverage;
this.RoundtripTimeMax = pc.RoundtripTimeMax;
this.RoundtripTimeMin= pc.RoundtripTimeMin;
this.RoundtripTimeCategory = pc.RoundtripTimeCategory;
}
#region public fields,enums
/// <summary>
/// A Ping állapot ezen időpillanattól kezdődően állt/áll fenn
/// </summary>
public DateTime StartTimestamp;
/// <summary>
/// A Ping állapot ezen időpillanattól kezdődően állt/áll fenn
/// </summary>
public DateTime LastTimestamp;
/// <summary>
/// Az állapot ilyen válaszidőt jelent (valójában ez is egy kategória, de egy konkrét idő érték jellemzi)
/// </summary>
public int RoundtripTime;
/// <summary>
/// A ping ciklusban végrehajtott ping-ek maximális válaszideje
/// </summary>
public int RoundtripTimeMax=-1;
/// <summary>
/// A ping ciklusban végrehajtott ping-ek minimális válaszideje
/// </summary>
public int RoundtripTimeMin=-1;
/// <summary>
/// A pontos válaszidők átlaga
/// </summary>
public int RoundtripTimeAverage;
/// <summary>
/// Az állapot ilyen válaszidő kategóriát jelent
/// </summary>
public RoundTripTimeCategory RoundtripTimeCategory;
/// <summary>
/// Az állapot ilyen IPStatus kategóriát jelent
/// </summary>
public IPStatusCategory StatusCategory;
/// <summary>
/// Ebben a státus állapotban ennyi csomag került kiküldésre
/// </summary>
public int PackagesSent;
/// <summary>
/// Ebben a státus állapotban ennyi csomag veszett el nem Success
/// </summary>
public int PackagesLost;
/// <summary>
/// Ebben a státus állapotban az elveszett csomagokra utaló státusz
/// </summary>
public LostPackageCategory PackagesSentCategory;
/// <summary>
/// A ping ciklusok száma ebben az egységben
/// </summary>
public int NumberOfCycles;
/// <summary>
/// Válasz státusz kategóriák; minél nagyobb az érték, annál kevesebbet tudunk a hiba okáról.
/// </summary>
public enum IPStatusCategory { Success = 0, TimedOut = 10, PortUnreachable = 20, HostUnreachable = 30, NetworkUnreachable = 40, Failed = 50, NotExecuted = 100, }
public enum LostPackageCategory { Excellent = 0, Good = 1, Acceptable = 2, Bad = 3, }
public enum RoundTripTimeCategory { Q1 = 0, Q2 = 1, Q3 = 2, Q4 = 3, }
#endregion public fields,enums
#region isDifferent
/// <summary>
/// Eldönti, hogy a két objektum azonosnak tekinthető-e, vagy sem
/// </summary>
/// <param name="pc"></param>
/// <returns></returns>
public bool isDifferent(PingCycle pc)
{
return this.StatusCategory != pc.StatusCategory
|| this.RoundtripTime != pc.RoundtripTime;
}
#endregion isDifferent
#region Execute
/// <summary>
/// Egy ping ciklus végrehajtása;
/// </summary>
/// <returns>
/// StatusCategory: értéke NotExecuted értéktől különbözni fog.
/// StartTimestamp: értéke a hívás időpillanata lesz.
/// PackagesLost: a nem Success-sel visszatérő ping-ek száma
/// RoundtripTimeCategory: a válaszidő kategória értéke
/// </returns>
public PingCycle Execute()
{
this.StartTimestamp = DateTime.Now;
this.LastTimestamp = this.StartTimestamp;
PingReply pr;
for (var i = 0; i < this.PackagesSent; i++)
{
pr = null;
try { pr = PingTool.Ping(this.HostNameOrAddress, (int)PingTimeout); }//egy ping kérés feladása
catch { }
AddResponse(pr, i + 1);//a ping válasz "bedolgozása" a pingciklus-állapotba
}
this.PackagesSentCategory = GetLostPackageCategory();
this.RoundtripTime = Pinger.RoundTripTimeLimits.LastOrDefault(x => x <= this.RoundtripTimeAverage);
var RoundTripTimeyCategoryValue = Pinger.RoundTripTimeyCategoryLimits.LastOrDefault(x => x < this.RoundtripTimeAverage);
var RoundTripTimeyCategoryIndex = Pinger.RoundTripTimeyCategoryLimits.FindIndex(x => x == RoundTripTimeyCategoryValue);
this.RoundtripTimeCategory = RoundTripTimeyCategoryIndex == 0 ? RoundTripTimeCategory.Q1
: RoundTripTimeyCategoryIndex == 1 ? RoundTripTimeCategory.Q2
: RoundTripTimeyCategoryIndex == 2 ? RoundTripTimeCategory.Q3
: RoundTripTimeCategory.Q4;
return this;
}
#endregion Execute
#region private elemek
/// <summary>
/// a ping célcíme
/// </summary>
private string HostNameOrAddress;
/// <summary>
/// Az egyes ping kérések timeout-ja
/// </summary>
private int PingTimeout;
/// <summary>
/// A ping válasz bedolgozása a pingciklus státuszba
/// </summary>
/// <param name="pr">a ping válasza</param>
/// <param name="i">a ping kérés indexe; 1,2,....</param>
private void AddResponse(PingReply pr, int i)
{
var ipsCat = GetIPStatusCategory(pr);
if (ipsCat==IPStatusCategory.Success)
{
int prroundtriptime = pr.RoundtripTime >= int.MaxValue ? int.MaxValue : (int)pr.RoundtripTime;
this.RoundtripTimeMin = prroundtriptime < this.RoundtripTimeMin || this.RoundtripTimeMin ==-1 ? prroundtriptime : this.RoundtripTimeMin;
this.RoundtripTimeMax = prroundtriptime > this.RoundtripTimeMax || this.RoundtripTimeMax == -1 ? prroundtriptime : this.RoundtripTimeMax;
this.RoundtripTimeAverage = ((i - 1) * this.RoundtripTimeAverage + prroundtriptime) / i;// az átlagos válaszidőt tárolja
}
else { this.PackagesLost++; }
if (ipsCat < this.StatusCategory) { this.StatusCategory = ipsCat; }// a legjobb státuszt tárolja
}
/// <summary>
/// Visszaadja az elveszett és összes csomagok száma alapján a lostpackagecategory értéket
/// </summary>
/// <param name="packageslost">az elveszett csomagok száma</param>
/// <param name="packagessent">az összes csomagok száma</param>
/// <returns></returns>
public LostPackageCategory GetLostPackageCategory()
{
double packagelostratio = (double)this.PackagesLost / (double)this.PackagesSent;
return packagelostratio == 0 ? PingCycle.LostPackageCategory.Excellent
: packagelostratio < 0.1 ? PingCycle.LostPackageCategory.Good
: packagelostratio < 0.3 ? PingCycle.LostPackageCategory.Acceptable
: PingCycle.LostPackageCategory.Bad;
}
/// <summary>
/// Visszaadja, hogy a PingReply adat alapján a válasz melyik státusz kategóriába tartozik
/// </summary>
/// <param name="pr"></param>
/// <returns></returns>
private static IPStatusCategory GetIPStatusCategory(PingReply pr)
{
//if (new Random().Next(0, 9) < 3) { return IPStatusCategory.Failed; }
if (pr == null) { return IPStatusCategory.Failed; }
switch (pr.Status)
{
case IPStatus.Success: return IPStatusCategory.Success;//Success = 0,The ICMP echo request succeeded; an ICMP echo reply was received. When you get this status code, the other System.Net.NetworkInformation.PingReply properties contain valid data.
case IPStatus.DestinationNetworkUnreachable: //DestinationNetworkUnreachable = 11002,The ICMP echo request failed because the network that contains the destination computer is not reachable.
return IPStatusCategory.NetworkUnreachable;
case IPStatus.BadRoute: //BadRoute = 11012,The ICMP echo request failed because there is no valid route between the source and destination computers.
case IPStatus.DestinationUnreachable: //DestinationUnreachable = 11040,The ICMP echo request failed because the destination computer that is specified in an ICMP echo message is not reachable; the exact cause of problem is unknown.
case IPStatus.DestinationHostUnreachable: //DestinationHostUnreachable = 11003,The ICMP echo request failed because the destination computer is not reachable.
return IPStatusCategory.HostUnreachable;
case IPStatus.TtlReassemblyTimeExceeded://TtlReassemblyTimeExceeded = 11014,The ICMP echo request failed because the packet was divided into fragments for transmission and all of the fragments were not received within the time allottedfor reassembly. RFC 2460 (available at www.ietf.org) specifies 60 seconds as the time limit within which all packet fragments must be received.
case IPStatus.TtlExpired://TtlExpired = 11013,The ICMP echo request failed because its Time to Live (TTL) value reached zero, causing the forwarding node (router or gateway) to discard the packet.
case IPStatus.TimeExceeded: //TimeExceeded = 11041,The ICMP echo request failed because its Time to Live (TTL) value reached zero, causing the forwarding node (router or gateway) to discard the packet.
case IPStatus.TimedOut: //TimedOut = 11010,The ICMP echo Reply was not received within the allotted time. The default time allowed for replies is 5 seconds. You can change this value using theOverload:System.Net.NetworkInformation.Ping.Send or Overload:System.Net.NetworkInformation.Ping.SendAsync methods that take a timeout parameter.
return IPStatusCategory.TimedOut;
//DestinationProhibited = 11004,The ICMPv6 echo request failed because contact with the destination computer is administratively prohibited. This value applies only to IPv6.
case IPStatus.DestinationProtocolUnreachable://DestinationProtocolUnreachable = 11004, The ICMP echo request failed because the destination computer that is specified in an ICMP echo message is not reachable, because it does not support the packet'sprotocol. This value applies only to IPv4. This value is described in IETF RFC 1812 as Communication Administratively Prohibited.
case IPStatus.DestinationPortUnreachable: //DestinationPortUnreachable = 11005,Summary: The ICMP echo request failed because the port on the destination computer is not available.
case IPStatus.Unknown://Unknown = -1,The ICMP echo request failed for an unknown reason.
case IPStatus.NoResources: //NoResources = 11006,Summary: The ICMP echo request failed because of insufficient network resources.
case IPStatus.BadOption: //BadOption = 11007,The ICMP echo request failed because it contains an invalid option.
case IPStatus.HardwareError: //HardwareError = 11008,The ICMP echo request failed because of a hardware error.
case IPStatus.PacketTooBig: //PacketTooBig = 11009,The ICMP echo request failed because the packet containing the request is larger than the maximum transmission unit (MTU) of a node (router or gateway) located between the source and destination. The MTU defines the maximum size of a transmittable packet.
case IPStatus.ParameterProblem: //ParameterProblem = 11015,The ICMP echo request failed because a node (router or gateway) encountered problems while processing the packet header. This is the status if, for example, the header contains invalid field data or an unrecognized option.
case IPStatus.SourceQuench: //SourceQuench = 11016,The ICMP echo request failed because the packet was discarded. This occurs when the source computer's output queue has insufficient storage space, or when packetsarrive at the destination too quickly to be processed.
case IPStatus.BadDestination: //BadDestination = 11018,The ICMP echo request failed because the destination IP address cannot receive ICMP echo requests or should never appear in the destination address field ofany IP datagram. For example, calling Overload:System.Net.NetworkInformation.Ping.Send and specifying IP address "000.0.0.0" returns this status.
case IPStatus.BadHeader: //BadHeader = 11042,The ICMP echo request failed because the header is invalid.
case IPStatus.UnrecognizedNextHeader://UnrecognizedNextHeader = 11043,The ICMP echo request failed because the Next Header field does not contain a recognized value. The Next Header field indicates the extension header type (ifpresent) or the protocol above the IP layer, for example, TCP or UDP.
case IPStatus.IcmpError: //IcmpError = 11044,The ICMP echo request failed because of an ICMP protocol error.
case IPStatus.DestinationScopeMismatch://DestinationScopeMismatch = 11045, The ICMP echo request failed because the source address and destination address that are specified in an ICMP echo message are not in the same scope. This istypically caused by a router forwarding a packet using an interface that is outside the scope of the source address. Address scopes (link-local, site-local, andglobal scope) determine where on the network an address is valid. }
return IPStatusCategory.Failed;
}
return IPStatusCategory.Failed;
}
#endregion private elemek
}
#endregion PingCycle class
public enum PingerStatus { NotExisting = 2, Still = 1, Operating = 0, }
}
/// <summary>
/// TCP Ping eszközök
/// </summary>
public static class PingTool
{
/// <summary>
/// Elérhető e az állomás?
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
/// <returns></returns>
public static bool IsHostAccessible(string hostNameOrAddress, int timeOut = 1000)
{
PingReply reply = Ping(hostNameOrAddress, timeOut);
return reply.Status == IPStatus.Success;
}
/// <summary>
/// Visszadja az állomás ping idejét (millisecundum)
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
/// <returns></returns>
public static long GetPingTime(string hostNameOrAddress, int timeOut = 1000)
{
PingReply reply = Ping(hostNameOrAddress, timeOut);
return reply.RoundtripTime;
}
/// <summary>
/// Visszadja az állomás ping szerinti státuszát (IPStatus)
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
///
/// <returns></returns>
public static IPStatus GetPingStatus(string hostNameOrAddress, int timeOut = 1000)
{
PingReply reply = Ping(hostNameOrAddress, timeOut);
return reply.Status;
}
/// <summary>
/// Ping
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
/// <returns>PingReply</returns>
public static PingReply Ping(string hostNameOrAddress, int timeOut = 1000)
{
Ping ping = new Ping();
return ping.Send(hostNameOrAddress, timeOut);
}
/// <summary>
/// Ping specifikált adatokkal
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
/// <param name="buffer">ping adatok</param>
/// <returns>PingReply</returns>
public static PingReply Ping(string hostNameOrAddress, int timeOut, byte[] buffer)
{
if (buffer.Length > 65500)
{
throw new ArgumentException("Ping data too big! Maximum 65500 bytes allowed!");
}
Ping ping = new Ping();
return ping.Send(hostNameOrAddress, timeOut, buffer);
}
/// <summary>
/// Ping specifikált adatokkal és beállításokkal (PingOptions)
/// </summary>
/// <param name="hostNameOrAddress">Ip, vagy host név</param>
/// <param name="timeOut">timeout</param>
/// <param name="buffer">ping adatok</param>
/// <param name="options">ping beállítások</param>
/// <returns>PingReply</returns>
public static PingReply Ping(string hostNameOrAddress, int timeOut, byte[] buffer, PingOptions options)
{
if (buffer.Length > 65500)
{
throw new ArgumentException("Ping data too big! Maximum 65500 bytes allowed!");
}
Ping ping = new Ping();
return ping.Send(hostNameOrAddress, timeOut, buffer, options);
}
}
/// <summary>
/// IPv4 kezeléssel kapcsolatos eszközök
/// </summary>
public static class IPv4Tool
{
/// <summary>
/// Visszad egy IPAddress osztályt, amit a megadott byte értékekből épít fel
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static IPAddress BuildIPAddress(params byte[] ip)
{
if (ip.Length != 4)
{
throw new ArgumentException("Invalid IP! Specific 4 byte value for valid IP address!");
}
return new IPAddress(ip);
}
public static IPAddress BuildIPAddress(string ipOrHostname)
{
IPAddress ip;
if (IPAddress.TryParse(ipOrHostname, out ip))
{
// IP
return ip;
}
else
{
// Hostname
try
{
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(ipOrHostname);
foreach (var address in hostEntry.AddressList)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return address;
}
}
throw new ArgumentException(String.Format("Bad input argument! (Argument is not Ip or DNS resorvable host name.)", ipOrHostname));
}
catch (Exception ex)
{
throw new ArgumentException(String.Format("Bad input argument! (Argument is not Ip or DNS resorvable host name.)", ipOrHostname), ex);
}
}
}
}
/// <summary>
/// MAC address lekérdezése IP alapján
/// </summary>
public static class MACTool
{
/// <summary>
/// Gets the MAC address (<see cref="PhysicalAddress"/>) associated with the specified IP.
/// </summary>
/// <param name="ipAddress">The remote IP address.</param>
/// <returns>The remote machine's MAC address.</returns>
public static PhysicalAddress GetMacAddress(IPAddress ipAddress)
{
const int MacAddressLength = 6;
int length = MacAddressLength;
var macBytes = new byte[MacAddressLength];
SendARP(BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0), 0, macBytes, ref length);
return new PhysicalAddress(macBytes);
}
public static PhysicalAddress GetMacAddress(string ipAddressOrHostName)
{
return MACTool.GetMacAddress(IPv4Tool.BuildIPAddress(ipAddressOrHostName));
}
public static PhysicalAddress GetMacAddress(params byte[] ipAddress)
{
return MACTool.GetMacAddress(IPv4Tool.BuildIPAddress(ipAddress));
}
public static string ToString(this PhysicalAddress mac, char byteSeparator)
{
return HexString.ByteArrayToHexViaLookup32(mac.GetAddressBytes(), byteSeparator);
}
/// <summary>
/// Netbiostól kér a mac címet, csak netbiost megvalósító eszközökre működik!!!
/// Elég lassú...
/// </summary>
/// <param name="ipAddress"></param>
/// <returns></returns>
public static string GetMacAddressFromNetBios(string ipAddress)
{
string macAddress = string.Empty;
if (!PingTool.IsHostAccessible(ipAddress))
{
return String.Empty;
}
try
{
ProcessStartInfo processStartInfo = new ProcessStartInfo();
Process process = new Process();
if (Environment.Is64BitOperatingSystem)
{
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + "\\sysnative";
processStartInfo.FileName = Path.Combine(filePath, "nbtstat");
}
else
{
processStartInfo.FileName = "nbtstat";
}
processStartInfo.RedirectStandardInput = false;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.Arguments = "-a " + ipAddress;
processStartInfo.UseShellExecute = false;
process = Process.Start(processStartInfo);
string line = null;
do
{
line = macAddress = process.StandardOutput.ReadLine();
if (line != null)
{
if (macAddress.Trim().ToLower().IndexOf("mac address", 0) > -1)
{
macAddress = line;
break;
}
}
} while (line != null);
process.WaitForExit();
if (macAddress.IndexOf('=') > -1)
{
macAddress = macAddress.Substring(macAddress.IndexOf('=') + 1);
}
macAddress = macAddress.Trim();
}
catch (Exception e)
{
// Something unexpected happened? Inform the user
// The possibilities are:
// 1.That the machine is not on the network currently
// 2. The IP address/hostname supplied are not on the same network
// 3. The host was not found on the same subnet or could not be
// resolved
}
return macAddress;
}
/// <summary>
/// ARP query kiküldése
/// </summary>
/// <param name="DestIP"></param>
/// <param name="SrcIP"></param>
/// <param name="pMacAddr"></param>
/// <param name="PhyAddrLen"></param>
/// <returns></returns>
// http://www.codeproject.com/KB/IP/host_info_within_network.aspx
[System.Runtime.InteropServices.DllImport("iphlpapi.dll", ExactSpelling = true)]
static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref int PhyAddrLen);
}
public static class HexString
{
private static readonly uint[] _lookup32 = CreateLookup32();
private static uint[] CreateLookup32()
{
var result = new uint[256];
for (int i = 0; i < 256; i++)
{
string s = i.ToString("X2");
result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
}
return result;
}
public static string ByteArrayToHexViaLookup32(byte[] bytes, char separator)
{
var lookup32 = _lookup32;
byte multipier = 2;
int length = bytes.Length * 2;
if (separator != '\0')
{
length = bytes.Length * 3 - 1;
multipier = 3;
}
var result = new char[length];
for (int i = 0; i < bytes.Length; i++)
{
var val = lookup32[bytes[i]];
result[multipier * i] = (char)val;
result[multipier * i + 1] = (char)(val >> 16);
if (separator != '\0' && i != bytes.Length - 1)
{
result[multipier * i + 2] = separator;
}
}
return new string(result);
}
}
}