/ * * IP Helper Function provides a lot of powerful, using simple network functions * * Here is a function of two calling gettcptable, settcptable, which will be used: * Use gettcptable to enumerate TCP port connection, simulate netstat * Use settcptable to turn off a TCP connection, so settcptable only supports deleting a TCP connection function * * Code by yztgx at 2005-1-11 * Reference: msnd (http://msdn.microsoft.com/library/default.asp ? URL = / library / en-us / iphlp / iphlp / setipstatistics.asp /
#include "iphlpapi.h" #include
#pragma comment (lib, "iphlpapi.lib") # Pragma Comment (LIB, "WS2_32.LIB")
Static char TCPState [] [32] = {"???", "listening", "syn_sent", "seen_received", "establish", "fin_wait", "fin_wait", "closing" "," Last_Ack "," Time_Wait "};
DWORD enuMtcptable () {pmib_tcptable ptcptable = null; dword dwsize = 0; dword dwretval = error_success;
Struct in_addr rip; struct in_addr lip; char szrip [32] = {0}; char SZLIP [32] = {0}; // Received the true length required for PTCPTABLE, DWSIZE IF (PTCPTable, & DWSize, True) = = Error_INSUFFICIENT_BUFFER) {ptcptable = (miB_tcptable *) Malloc ((uint) dwsize;} else return dwretval;
Printf ("Active Connections / N / N"); Printf ("Proto / T%-24S%-24S% S / N", "Local Address", "Foreign Address", "State");
IF (DWRETVAL = GettcPtable (Ptcptable, & Dwsize, True) == NO_ERROR) {for (int i = 0; i <(int) ptcptable-> dwnumentries; i ) {rip.s_un.s_addr = ptcptable-> Table [ i] .dwremoteaddr; lip.s_un.s_addr = ptcptable-> table [i] .dwlocaladdr; // listening to port, remote host port is 0, but the function returns value, I don't know how it considers IF (PTCPTABLE -> Table [i] .dwstate == mib_tcp_state_listen) PTCPTable-> Table [i] .dwremoteport = 0; // dwlocalport, dwremoteport is network byte _snprintf (Szlip, sizeof (szlip), "% s:% d", INET_NTOA (LIP), HTONS ((u_short) ptcptable-> table [i] .dwlocalport)); _SnPrintf (SzrIP, SizeOf (Szrip), "% S:% D", INT_NTOA (RIP), HTONS ((u_short) PTCPTABLE -> Table [i] .dwremoteport); Printf ("TCP / T%-24S%-24S% S / N", Szlip, Szrip, TcpState [ptcptable-> table [i] .dwstate]);}} {printf ( "/ tCall to GetTcpTable failed./n"); LPVOID lpMsgBuf; if (FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), // Def AULT LANGUAGE (LPTSTR) & lpmsgbuf, 0, null) {Printf ("/ TERROR:% S", LPMSGBUF);} localfree (lpmsgbuf);} GlobalFree (ptcptable); return dwretval;}