用GetTcpTable可以獲取到本進程ip地址,端口,遠程IP地址和端口,但是無法將該套接字與進程名聯系起來!可以利用AllocateAndGetTcpExTableFromStack來實現,但這個函數在win7版失效了,可能是因為覺得這個還比較麻煩吧,在win7環境下,我們可以用GetExtendTcpTable來實現上面的功能,該實現在下次給出。
#include <stdio.h> #include <WinSock2.h> #include <stdio.h> #include <iphlpapi.h> #include <tlhelp32.h> #include <> #include <vector> #include <Psapi.h> comment(lib,"ws2_32.lib") comment(lib,"Iphlpapi.lib") comment (lib,"Psapi.lib") typedef DWORD dwState; DWORD dwLocalPort; DWORD dwRemotePort; DWORD dwProcessId; szLocalAddr; szRemoteAddr; szProcessName; }TCPINFO,* typedef } MIB_TCPEXROW, * typedef } MIB_TCPEXTABLE, * typedef } MIB_UDPEXROW, * typedef } MIB_UDPEXTABLE, * typedef DWORD (WINAPI *PFNAllocateAndGetTcpExTableFromStack)(PMIB_TCPEXTABLE * typedef DWORD (WINAPI *PFNAllocateAndGetUdpExTableFromStack)(PMIB_UDPEXTABLE * vector<TCPINFO> vector<TCPINFO> vec = (vector<TCPINFO>::iterator iter = vec.begin(); iter != vec.end(); iter++ State = ConvertStateToString(iter-> printf(,(iter->szLocalAddr).c_str(),iter->dwLocalPort,(iter->szRemoteAddr).c_str(),iter-> printf(,(iter->szProcessName).c_str(),iter-> vector<TCPINFO> vector<TCPINFO> DWORD dwSize = HMODULE hModule = ::LoadLibrary(); PFNAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStack = (PFNAllocateAndGetTcpExTableFromStack)::GetProcAddress(hModule, PFNAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStack = (PFNAllocateAndGetUdpExTableFromStack)::GetProcAddress(hModule, (pAllocateAndGetTcpExTableFromStack(&pTcpExTable, TRUE, GetProcessHeap(), , ) != printf( (pAllocateAndGetUdpExTableFromStack(&pUdpExTable, TRUE, GetProcessHeap(), , ) != printf( (unsigned count = ; count < pTcpExTable->dwNumEntries; count++ TcpInfo.dwState = pTcpExTable-> TcpInfo.dwRemotePort = htons((u_short)pTcpExTable->table[count].dwRemotePort); TcpInfo.dwLocalPort = htons((u_short)pTcpExTable->table[count].dwLocalPort); InetLocalAddr.s_addr = pTcpExTable-> InetRemoteAddr.s_addr = pTcpExTable-> TcpInfo.szLocalAddr = inet_ntoa(InetLocalAddr); TcpInfo.szRemoteAddr = inet_ntoa(InetRemoteAddr); TcpInfo.dwProcessId = pTcpExTable->table[count].dwProcessId; TcpInfo.szProcessName = GetProcessNameByPid(pTcpExTable->table[count].dwProcessId); vec.push_back(TcpInfo); ProcessPath[] = { HANDLE h_Process = OpenProcess(PROCESS_ALL_ACCESS, GetModuleFileNameEx(h_Process,NULL,ProcessPath, * ProcessName = ( *)strrchr(ProcessPath, *ProcessName = ProcessName++ szProcessName = : : : : : : : : : : : : : }