You can use GetTcpTable to obtain the IP address, port, remote IP address, and port of the current process. However, you cannot associate the socket with the process name! You can use AllocateAndGetTcpExTableFromStack to implement this function, but this function is invalid in win7. It may be because it is still troublesome. In win7, we can use GetExtendTcpTable to implement the above functions, this implementation will be provided next time.
#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 = : : : : : : : : : : : : : }