The getextendedtcptable function retrieves a table that contains a list of TCP endpoints available to the application.
C # signature:
[Dllimport ("iphlpapi. dll", setlasterror = true)]
Static extern uint getextendedtcptable (intptr ptcptable, ref int dwoutbuflen, bool sort, int ipversion, tcp_table_class tblclass, int reserved );
[Structlayout (layoutkind. Sequential)]
Public struct mib_tcprow_owner_pid
{
Public tcpstate state;
Public uint localaddr;
Public byte localport1;
Public byte localport2;
Public byte localport3;
Public byte localport4;
Public uint remoteaddr;
Public byte remoteport1;
Public byte remoteport2;
Public byte remoteport3;
Public byte remoteport4;
Public int owningpid;
}
[Structlayout (layoutkind. Sequential)]
Public struct mib_tcptable_owner_pid
{
Public uint dwnumentries;
Mib_tcprow_owner_pid table;
}
// Public tcprow [] getalltcpconnections ()
Public mib_tcprow_owner_pid [] getalltcpconnections ()
{
// Tcprow is my own class to display returned rows in a nice manner.
// Tcprow [] tTable;
Mib_tcprow_owner_pid [] tTable;
Int af_inet = 2; // ip_v4
Int buffsize = 0;
// How much memory do we need?
Uint ret = getextendedtcptable (intptr. Zero, ref buffsize, true, af_inet, tcp_table_class.tcp_table_owner_pid_all, 0 );
Intptr bufftable = marshal. allochglobal (buffsize );
Try
{
Ret = getextendedtcptable (bufftable, ref buffsize, true, af_inet, tcp_table_class.tcp_table_owner_pid_all, 0 );
If (Ret! = 0)
{
Return NULL;
}
// Get the number of entries in the table
// Mibtcptable tab = (mibtcptable) Marshal. ptrtostructure (bufftable, typeof (mibtcptable ));
Mib_tcptable_owner_pid tab = (mib_tcptable_owner_pid) Marshal. ptrtostructure (bufftable, typeof (mib_tcptable_owner_pid ));
// Intptr rowptr = (intptr) (long) bufftable + marshal. sizeof (Tab. numberofentries ));
Intptr rowptr = (intptr) (long) bufftable + marshal. sizeof (Tab. dwnumentries ));
// Buffer we will be returning
// TTable = new tcprow [tab. numberofentries];
TTable = new mib_tcprow_owner_pid [tab. dwnumentries];
// For (INT I = 0; I <tab. numberofentries; I ++)
For (INT I = 0; I <tab. dwnumentries; I ++)
{
// Mibtcprow_owner_pid tcprow = (mibtcprow_owner_pid) Marshal. ptrtostructure (rowptr, typeof (mibtcprow_owner_pid ));
Mib_tcprow_owner_pid tcprow = (mib_tcprow_owner_pid) Marshal. ptrtostructure (rowptr, typeof (mib_tcprow_owner_pid ));
// TTable [I] = new tcprow (tcprow );
TTable [I] = tcprow;
Rowptr = (intptr) (long) rowptr + marshal. sizeof (tcprow); // next entry
}
}
Finally
{
// Free the memory
Marshal. freehglobal (bufftable );
}
Return tTable;
}