-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.cs
1237 lines (1122 loc) · 43.9 KB
/
main.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
using System;
using System.Net;
using System.Text;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Net.NetworkInformation;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace IpHlpApidotnet
{
public enum Protocol { TCP, UDP, None };
/// <summary>
/// Store information concerning single TCP/UDP connection
/// </summary>
public class TCPUDPConnection
{
private int _dwState;
public int iState
{
get { return _dwState; }
set
{
if (_dwState != value)
{
_dwState = value;
_State = Utils.StateToStr(value);
}
}
}
private static TCPUDPConnections _conns = null;
public TCPUDPConnection(TCPUDPConnections conns) : base()
{
_conns = conns;
}
public string GetHostName(IPEndPoint HostAddress)
{
return Utils.GetHostName(HostAddress, _conns.LocalHostName);
}
private bool _IsResolveIP = true;
public bool IsResolveIP
{
get { return _IsResolveIP; }
set { _IsResolveIP = value; }
}
private Protocol _Protocol;
public Protocol Protocol
{
get { return _Protocol; }
set { _Protocol = value; }
}
private string _State = String.Empty;
public string State
{
get { return _State; }
}
private IPEndPoint _OldLocalHostName;
private IPEndPoint _OldRemoteHostName;
private string _LocalAddress = String.Empty;
private string _RemoteAddress = String.Empty;
private void SaveHostName(bool IsLocalHostName)
{
if (IsLocalHostName)
{
this._LocalAddress = GetHostName(this._Local);
this._OldLocalHostName = this._Local;
}
else
{
this._RemoteAddress = GetHostName(this._Remote);
this._OldRemoteHostName = this._Remote;
}
}
public string LocalAddress
{
get
{
if (this._OldLocalHostName == this._Local)
{
if (this._LocalAddress.Trim() == String.Empty)
{
this.SaveHostName(true);
}
}
else
{
this.SaveHostName(true);
}
return this._LocalAddress;
}
}
public string RemoteAddress
{
get
{
if (this._OldRemoteHostName == this._Remote)
{
if (this._RemoteAddress.Trim() == String.Empty)
{
this.SaveHostName(false);
}
}
else
{
this.SaveHostName(false);
}
return this._RemoteAddress;
}
}
// Return exist local address or "unknown" if address if empty
public string TryGetLocalAddress()
{
return (this._LocalAddress.Trim() == String.Empty) ? "unknown" : this._LocalAddress;
}
// Return exist remote address or "unknown" if address if empty
public string TryGetRemoteAddress()
{
return (this._RemoteAddress.Trim() == String.Empty) ? "unknown" : this._RemoteAddress;
}
private IPEndPoint _Local = null;
public IPEndPoint Local //LocalAddress
{
get { return this._Local; }
set
{
if (this._Local != value)
{
this._Local = value;
}
}
}
private IPEndPoint _Remote;
public IPEndPoint Remote //RemoteAddress
{
get { return this._Remote; }
set
{
if (this._Remote != value)
{
this._Remote = value;
}
}
}
private int _dwOwningPid;
public int PID
{
get { return this._dwOwningPid; }
set
{
if (this._dwOwningPid != value)
{
this._dwOwningPid = value;
}
}
}
private void SaveProcessID()
{
this._ProcessName = Utils.GetProcessNameByPID(this._dwOwningPid);
this._OldProcessID = this._dwOwningPid;
}
private int _OldProcessID = -1;
private string _ProcessName = String.Empty;
public string ProcessName
{
get
{
if (this._OldProcessID == this._dwOwningPid)
{
if (this._ProcessName.Trim() == String.Empty)
{
this.SaveProcessID();
}
}
else
{
this.SaveProcessID();
}
return this._ProcessName;
}
}
private DateTime _WasActiveAt = DateTime.MinValue;
public DateTime WasActiveAt
{
get { return _WasActiveAt; }
internal set { _WasActiveAt = value; }
}
private Object _Tag = null;
public Object Tag
{
get { return this._Tag; }
set { this._Tag = value; }
}
}
public class SortConnections : IComparer<TCPUDPConnection>
{
/// <summary>
/// Method is used to compare two <seealso cref="TCPUDPConnection"/>.
///
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public virtual int CompareConnections(TCPUDPConnection first, TCPUDPConnection second)
{
int i;
i = Utils.CompareIPEndPoints(first.Local, second.Local);
if (i != 0)
return i;
if (first.Protocol == Protocol.TCP &&
second.Protocol == Protocol.TCP)
{
i = Utils.CompareIPEndPoints(first.Remote, second.Remote);
if (i != 0)
return i;
}
i = first.PID - second.PID;
if (i != 0)
return i;
if (first.Protocol == second.Protocol)
return 0;
if (first.Protocol == Protocol.TCP)
return -1;
else
return 1;
}
#region IComparer<TCPUDPConnection> Members
public int Compare(TCPUDPConnection x, TCPUDPConnection y)
{
return this.CompareConnections(x, y);
}
#endregion
}
/// <summary>
/// Store information concerning TCP/UDP connections
/// </summary>
public class TCPUDPConnections : IEnumerable<TCPUDPConnection>
{
private List<TCPUDPConnection> _list;
System.Timers.Timer _timer = null;
private int _DeadConnsMultiplier = 10; //Collect dead connections each 5 sec.
private int _TimerCounter = -1;
private string _LocalHostName = String.Empty;
public TCPUDPConnections()
{
_LocalHostName = Utils.GetLocalHostName();
_list = new List<TCPUDPConnection>();
_timer = new System.Timers.Timer();
_timer.Interval = 1000; // Refresh list every 1 sec.
_timer.Elapsed += new System.Timers.ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
}
/// <summary>
/// Coefficient multiplies on AutoRefresh timer interval. The parameter determinate how
/// often detecting of dead connections occures.
/// </summary>
public int DeadConnsMultiplier
{
get { return _DeadConnsMultiplier; }
set { _DeadConnsMultiplier = value; }
}
/// <summary>
/// AutoRefresh timer.
/// </summary>
public System.Timers.Timer Timer
{
get { return _timer; }
}
public delegate void ItemAddedEvent(Object sender, TCPUDPConnection item);
/// <summary>
/// Event occures when <seealso cref="TCPUDPConnection"/> deleted.
/// </summary>
public event ItemAddedEvent ItemAdded;
private void ItemAddedEventHandler(TCPUDPConnection item)
{
if (ItemAdded != null)
{
ItemAdded(this, item);
}
}
public delegate void ItemChangedEvent(Object sender, TCPUDPConnection item, int Pos);
/// <summary>
/// Event occures when <seealso cref="TCPUDPConnection"/> changed.
/// </summary>
public event ItemChangedEvent ItemChanged;
private void ItemChangedEventHandler(TCPUDPConnection item, int Pos)
{
if (ItemChanged != null)
{
ItemChanged(this, item, Pos);
}
}
public delegate void ItemInsertedEvent(Object sender, TCPUDPConnection item, int Position);
/// <summary>
/// Event occures when <seealso cref="TCPUDPConnection"/> inserted into list.
/// </summary>
public event ItemInsertedEvent ItemInserted;
private void ItemInsertedEventHandler(TCPUDPConnection item, int Position)
{
if (ItemInserted != null)
{
ItemInserted(this, item, Position);
}
}
public delegate void ItemDeletedEvent(Object sender, TCPUDPConnection item, int Position);
/// <summary>
/// Event occures when <seealso cref="TCPUDPConnection"/> deleted from list.
/// </summary>
public event ItemDeletedEvent ItemDeleted;
private void ItemDeletedEventHandler(TCPUDPConnection item, int Position)
{
if (ItemDeleted != null)
{
ItemDeleted(this, item, Position);
}
}
void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.Refresh();
}
/// <summary>
/// Refresh connections list.
/// </summary>
public void Refresh()
{
lock (this)
{
this._LastRefreshDateTime = DateTime.Now;
this.GetTcpConnections();
this.GetUdpConnections();
_TimerCounter++;
if (_DeadConnsMultiplier == _TimerCounter)
{
this.CheckForClosedConnections();
_TimerCounter = -1;
}
}
}
/// <summary>
/// Refresh TCP connections list.
/// </summary>
public void RefreshTCP()
{
lock (this)
{
this._LastRefreshDateTime = DateTime.Now;
this.GetTcpConnections();
_TimerCounter++;
if (_DeadConnsMultiplier == _TimerCounter)
{
this.CheckForClosedConnections();
_TimerCounter = -1;
}
}
}
/// <summary>
/// Refresh UDP connections list.
/// </summary>
public void RefreshUDP()
{
lock (this)
{
this._LastRefreshDateTime = DateTime.Now;
this.GetUdpConnections();
_TimerCounter++;
if (_DeadConnsMultiplier == _TimerCounter)
{
this.CheckForClosedConnections();
_TimerCounter = -1;
}
}
}
/// <summary>
/// Get last refresh <seealso cref="DateTime"/>.
/// </summary>
private DateTime _LastRefreshDateTime = DateTime.MinValue;
public DateTime LastRefreshDateTime
{
get { return _LastRefreshDateTime; }
}
public void StopAutoRefresh()
{
_timer.Stop();
}
public void StartAutoRefresh()
{
_timer.Start();
}
/// <summary>
/// Enable or Disable connections list auto refresh.
/// </summary>
public bool AutoRefresh
{
get { return _timer.Enabled; }
set { _timer.Enabled = value; }
}
/// <summary>
/// Add new <seealso cref="TCPUDPConnection"/> connection.
/// </summary>
/// <param name="item"></param>
public void Add(TCPUDPConnection item)
{
int Pos = 0;
TCPUDPConnection conn = IndexOf(item, out Pos);
if (conn == null)
{
item.WasActiveAt = DateTime.Now;
if (Pos > -1)
{
this.Insert(Pos, item);
}
else
{
_list.Add(item);
ItemAddedEventHandler(item);
}
}
else
{
_list[Pos].WasActiveAt = DateTime.Now;
if (conn.iState != item.iState ||
conn.PID != item.PID)
{
conn.iState = item.iState;
conn.PID = item.PID;
ItemChangedEventHandler(conn, Pos);
}
}
}
public int Count
{
get { return _list.Count; }
}
public TCPUDPConnection this[int index]
{
get { return _list[index]; }
set { _list[index] = value; }
}
private SortConnections _connComp = new SortConnections();
public void Sort()
{
_list.Sort(_connComp);
}
public TCPUDPConnection IndexOf(TCPUDPConnection item, out int Pos)
{
int index = -1;
foreach (TCPUDPConnection conn in _list)
{
index++;
int i = _connComp.CompareConnections(item, conn);
if (i == 0)
{
Pos = index;
return conn;
}
if (i > 0) // If current an item more then conn, try to compare with next one until finding equal or less.
{
continue; //Skip
}
if (i < 0) // If there is an item in list with row less then current, insert current before this one.
{
Pos = index;
return null;
}
}
Pos = -1;
return null;
}
/// <summary>
/// Method detect and remove from list all dead connections.
/// </summary>
public void CheckForClosedConnections()
{
int interval = (int)_timer.Interval * this._DeadConnsMultiplier;
//Remove item from the end of the list
for (int index = _list.Count - 1; index >= 0; index--)
{
TCPUDPConnection conn = this[index];
TimeSpan diff = (this._LastRefreshDateTime - conn.WasActiveAt);
int interval1 = Math.Abs((int)diff.TotalMilliseconds);
if (interval1 > interval)
{
this.Remove(index);
}
}
}
public void Remove(int index)
{
TCPUDPConnection conn = this[index];
_list.RemoveAt(index);
this.ItemDeletedEventHandler(conn, index);
}
public void Insert(int index, TCPUDPConnection item)
{
_list.Insert(index, item);
ItemInsertedEventHandler(item, index);
}
public void GetTcpConnections()
{
int AF_INET = 2; // IP_v4
int buffSize = 20000;
byte[] buffer = new byte[buffSize];
int res = IPHlpAPI32Wrapper.GetExtendedTcpTable(buffer, out buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
if (res != Utils.NO_ERROR) //If there is no enouth memory to execute function
{
buffer = new byte[buffSize];
res = IPHlpAPI32Wrapper.GetExtendedTcpTable(buffer, out buffSize, true, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0);
if (res != Utils.NO_ERROR)
{
return;
}
}
int nOffset = 0;
// number of entry in the
int NumEntries = Convert.ToInt32(buffer[nOffset]);
nOffset += 4;
for (int i = 0; i < NumEntries; i++)
{
TCPUDPConnection row = new TCPUDPConnection(this);
// state
int st = Convert.ToInt32(buffer[nOffset]);
// state by ID
row.iState = st;
nOffset += 4;
row.Protocol = Protocol.TCP;
row.Local = Utils.BufferToIPEndPoint(buffer, ref nOffset, false);
row.Remote = Utils.BufferToIPEndPoint(buffer, ref nOffset, true);
row.PID = Utils.BufferToInt(buffer, ref nOffset);
this.Add(row);
}
}
public string LocalHostName
{
get { return _LocalHostName; }
}
public void GetUdpConnections()
{
int AF_INET = 2; // IP_v4
int buffSize = 20000;
byte[] buffer = new byte[buffSize];
int res = IPHlpAPI32Wrapper.GetExtendedUdpTable(buffer, out buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
if (res != Utils.NO_ERROR)
{
buffer = new byte[buffSize];
res = IPHlpAPI32Wrapper.GetExtendedUdpTable(buffer, out buffSize, true, AF_INET, UDP_TABLE_CLASS.UDP_TABLE_OWNER_PID, 0);
if (res != Utils.NO_ERROR)
{
return;
}
}
int nOffset = 0;
int NumEntries = Convert.ToInt32(buffer[nOffset]);
nOffset += 4;
for (int i = 0; i < NumEntries; i++)
{
TCPUDPConnection row = new TCPUDPConnection(this);
row.Protocol = Protocol.UDP;
row.Local = Utils.BufferToIPEndPoint(buffer, ref nOffset, false);
row.PID = Utils.BufferToInt(buffer, ref nOffset);
this.Add(row);
}
}
#region ThreadWorkers
// Time for sleep thread after processing all records
private int _ThreadWaitTimeSec = 2;
public int ThreadIdleTimeSec
{
get { return _ThreadWaitTimeSec; }
set { _ThreadWaitTimeSec = value; }
}
private object _singleRefreshHostNameThread = new object();
private void ThreadRefreshHostName()
{
// Only one copy of the function can be executed in thread in same time
if (Monitor.TryEnter(_singleRefreshHostNameThread))
{
try
{
int unknown_selected_index = 0;
var unknown_ip = String.Empty;
var is_local = false;
var temp = String.Empty;
while (true)
{
unknown_selected_index = 0;
unknown_ip = String.Empty;
is_local = false;
foreach (var con in _list)
{
if (con.TryGetLocalAddress() == "unknown")
{
unknown_ip = con.Local.Address.ToString();
is_local = true;
break;
}
if (con.TryGetRemoteAddress() == "unknown")
{
unknown_ip = con.Remote.Address.ToString();
break;
}
unknown_selected_index++;
}
// If all connections has host name, then wait
if (unknown_ip == String.Empty)
{
Thread.Sleep(ThreadIdleTimeSec * 1000);
continue;
}
Utils.FillHostNameCache(unknown_ip);
// Size of collection can be changed, while await dns response
try
{
if (unknown_selected_index < _list.Count)
{
if (is_local)
{
foreach (var connection in _list)
{
if (connection.Local.Address.ToString() == unknown_ip)
{
temp = connection.LocalAddress;
}
/*
if (_list[unknown_selected_index].Local.Address.ToString() == unknown_ip)
{
temp = _list[unknown_selected_index].LocalAddress;
}
*/
}
}
else
{
if (_list[unknown_selected_index].Remote.Address.ToString() == unknown_ip)
{
temp = _list[unknown_selected_index].RemoteAddress;
}
}
}
}
catch (Exception)
{
continue;
}
}
}
finally
{
Monitor.Exit(_singleRefreshHostNameThread);
}
}
}
public void RunRefreshHostName()
{
Thread RefreshHostNameThread = new Thread(ThreadRefreshHostName);
// Make thread background. Thread close, when main app thred is finish.
RefreshHostNameThread.IsBackground = true;
RefreshHostNameThread.Start();
}
#endregion
#region IEnumerable<TCPUDPConnection> Members
public IEnumerator<TCPUDPConnection> GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
#endregion
}
public class IPHelper
{
/*
* Tcp Struct
* */
public IpHlpApidotnet.MIB_TCPTABLE TcpConnections;
public IpHlpApidotnet.MIB_TCPSTATS TcpStats;
public IpHlpApidotnet.MIB_EXTCPTABLE TcpExConnections;
//public IpHlpApidotnet.MIB_TCPTABLE_OWNER_PID TcpExAllConnections;
/*
* Udp Struct
* */
public IpHlpApidotnet.MIB_UDPSTATS UdpStats;
public IpHlpApidotnet.MIB_UDPTABLE UdpConnections;
public IpHlpApidotnet.MIB_EXUDPTABLE UdpExConnections;
//public IpHlpApidotnet.MIB_UDPTABLE_OWNER_PID UdpExAllConnections;
public TCPUDPConnections Connections;
public IPHelper()
{
}
#region Tcp Functions
public void GetTcpStats()
{
TcpStats = new MIB_TCPSTATS();
IPHlpAPI32Wrapper.GetTcpStatistics(ref TcpStats);
}
public void GetExTcpConnections()
{
// the size of the MIB_EXTCPROW struct = 6*DWORD
int rowsize = 24;
int BufferSize = 100000;
// allocate a dumb memory space in order to retrieve nb of connection
IntPtr lpTable = Marshal.AllocHGlobal(BufferSize);
//getting infos
int res = IPHlpAPI32Wrapper.AllocateAndGetTcpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2);
if (res != Utils.NO_ERROR)
{
Debug.WriteLine("Error : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res);
return; // Error. You should handle it
}
int CurrentIndex = 0;
//get the number of entries in the table
int NumEntries = (int)Marshal.ReadIntPtr(lpTable);
lpTable = IntPtr.Zero;
// free allocated space in memory
Marshal.FreeHGlobal(lpTable);
///////////////////
// calculate the real buffer size nb of entrie * size of the struct for each entrie(24) + the dwNumEntries
BufferSize = (NumEntries * rowsize) + 4;
// make the struct to hold the resullts
TcpExConnections = new IpHlpApidotnet.MIB_EXTCPTABLE();
// Allocate memory
lpTable = Marshal.AllocHGlobal(BufferSize);
res = IPHlpAPI32Wrapper.AllocateAndGetTcpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2);
if (res != Utils.NO_ERROR)
{
Debug.WriteLine("Error : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res);
return; // Error. You should handle it
}
// New pointer of iterating throught the data
IntPtr current = lpTable;
CurrentIndex = 0;
// get the (again) the number of entries
NumEntries = (int)Marshal.ReadIntPtr(current);
TcpExConnections.dwNumEntries = NumEntries;
// Make the array of entries
TcpExConnections.table = new MIB_EXTCPROW[NumEntries];
// iterate the pointer of 4 (the size of the DWORD dwNumEntries)
CurrentIndex += 4;
current = (IntPtr)((int)current + CurrentIndex);
// for each entries
for (int i = 0; i < NumEntries; i++)
{
// The state of the connection (in string)
TcpExConnections.table[i].StrgState = Utils.StateToStr((int)Marshal.ReadIntPtr(current));
// The state of the connection (in ID)
TcpExConnections.table[i].iState = (int)Marshal.ReadIntPtr(current);
// iterate the pointer of 4
current = (IntPtr)((int)current + 4);
// get the local address of the connection
UInt32 localAddr = (UInt32)Marshal.ReadIntPtr(current);
// iterate the pointer of 4
current = (IntPtr)((int)current + 4);
// get the local port of the connection
UInt32 localPort = (UInt32)Marshal.ReadIntPtr(current);
// iterate the pointer of 4
current = (IntPtr)((int)current + 4);
// Store the local endpoint in the struct and convertthe port in decimal (ie convert_Port())
TcpExConnections.table[i].Local = new IPEndPoint(localAddr, (int)Utils.ConvertPort(localPort));
// get the remote address of the connection
UInt32 RemoteAddr = (UInt32)Marshal.ReadIntPtr(current);
// iterate the pointer of 4
current = (IntPtr)((int)current + 4);
UInt32 RemotePort = 0;
// if the remote address = 0 (0.0.0.0) the remote port is always 0
// else get the remote port
if (RemoteAddr != 0)
{
RemotePort = (UInt32)Marshal.ReadIntPtr(current);
RemotePort = Utils.ConvertPort(RemotePort);
}
current = (IntPtr)((int)current + 4);
// store the remote endpoint in the struct and convertthe port in decimal (ie convert_Port())
TcpExConnections.table[i].Remote = new IPEndPoint(RemoteAddr, (int)RemotePort);
// store the process ID
TcpExConnections.table[i].dwProcessId = (int)Marshal.ReadIntPtr(current);
// Store and get the process name in the struct
TcpExConnections.table[i].ProcessName = Utils.GetProcessNameByPID(TcpExConnections.table[i].dwProcessId);
current = (IntPtr)((int)current + 4);
}
// free the buffer
Marshal.FreeHGlobal(lpTable);
// re init the pointer
current = IntPtr.Zero;
}
public TcpConnectionInformation[] GetTcpConnectionsNative()
{
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
return properties.GetActiveTcpConnections();
}
public IPEndPoint[] GetUdpListeners()
{
return IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
}
public IPEndPoint[] GetTcpListeners()
{
return IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
}
public void GetTcpConnections()
{
byte[] buffer = new byte[20000]; // Start with 20.000 bytes left for information about tcp table
int pdwSize = 20000;
int res = IPHlpAPI32Wrapper.GetTcpTable(buffer, out pdwSize, true);
if (res != Utils.NO_ERROR)
{
buffer = new byte[pdwSize];
res = IPHlpAPI32Wrapper.GetTcpTable(buffer, out pdwSize, true);
if (res != 0)
return; // Error. You should handle it
}
TcpConnections = new IpHlpApidotnet.MIB_TCPTABLE();
int nOffset = 0;
// number of entry in the
TcpConnections.dwNumEntries = Convert.ToInt32(buffer[nOffset]);
nOffset += 4;
TcpConnections.table = new MIB_TCPROW[TcpConnections.dwNumEntries];
for (int i = 0; i < TcpConnections.dwNumEntries; i++)
{
// state
int st = Convert.ToInt32(buffer[nOffset]);
// state in string
TcpConnections.table[i].StrgState = Utils.StateToStr(st);
// state by ID
TcpConnections.table[i].iState = st;
nOffset += 4;
// local address
TcpConnections.table[i].Local = Utils.BufferToIPEndPoint(buffer, ref nOffset, false);
// remote address
TcpConnections.table[i].Remote = Utils.BufferToIPEndPoint(buffer, ref nOffset, true);
}
}
#endregion
#region Udp Functions
public void GetUdpStats()
{
UdpStats = new MIB_UDPSTATS();
IPHlpAPI32Wrapper.GetUdpStatistics(ref UdpStats);
}
public void GetUdpConnections()
{
byte[] buffer = new byte[20000]; // Start with 20.000 bytes left for information about tcp table
int pdwSize = 20000;
int res = IPHlpAPI32Wrapper.GetUdpTable(buffer, out pdwSize, true);
if (res != Utils.NO_ERROR)
{
buffer = new byte[pdwSize];
res = IPHlpAPI32Wrapper.GetUdpTable(buffer, out pdwSize, true);
if (res != Utils.NO_ERROR)
return; // Error. You should handle it
}
UdpConnections = new IpHlpApidotnet.MIB_UDPTABLE();
int nOffset = 0;
// number of entry in the
UdpConnections.dwNumEntries = Convert.ToInt32(buffer[nOffset]);
nOffset += 4;
UdpConnections.table = new MIB_UDPROW[UdpConnections.dwNumEntries];
for (int i = 0; i < UdpConnections.dwNumEntries; i++)
{
UdpConnections.table[i].Local = Utils.BufferToIPEndPoint(buffer, ref nOffset, false);//new IPEndPoint(IPAddress.Parse(LocalAdrr), LocalPort);
}
}
public void GetExUdpConnections()
{
// the size of the MIB_EXTCPROW struct = 4*DWORD
int rowsize = 12;
int BufferSize = 100000;
// allocate a dumb memory space in order to retrieve nb of connection
IntPtr lpTable = Marshal.AllocHGlobal(BufferSize);
//getting infos
int res = IPHlpAPI32Wrapper.AllocateAndGetUdpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2);
if (res != Utils.NO_ERROR)
{
Debug.WriteLine("Error : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res);
return; // Error. You should handle it
}
int CurrentIndex = 0;
//get the number of entries in the table
int NumEntries = (int)Marshal.ReadIntPtr(lpTable);
lpTable = IntPtr.Zero;
// free allocated space in memory
Marshal.FreeHGlobal(lpTable);
///////////////////
// calculate the real buffer size nb of entrie * size of the struct for each entrie(24) + the dwNumEntries
BufferSize = (NumEntries * rowsize) + 4;
// make the struct to hold the resullts
UdpExConnections = new IpHlpApidotnet.MIB_EXUDPTABLE();
// Allocate memory
lpTable = Marshal.AllocHGlobal(BufferSize);
res = IPHlpAPI32Wrapper.AllocateAndGetUdpExTableFromStack(ref lpTable, true, IPHlpAPI32Wrapper.GetProcessHeap(), 0, 2);
if (res != Utils.NO_ERROR)
{
Debug.WriteLine("Error : " + IPHlpAPI32Wrapper.GetAPIErrorMessageDescription(res) + " " + res);
return; // Error. You should handle it
}
// New pointer of iterating throught the data
IntPtr current = lpTable;
CurrentIndex = 0;
// get the (again) the number of entries
NumEntries = (int)Marshal.ReadIntPtr(current);
UdpExConnections.dwNumEntries = NumEntries;
// Make the array of entries
UdpExConnections.table = new MIB_EXUDPROW[NumEntries];
// iterate the pointer of 4 (the size of the DWORD dwNumEntries)