这问题都老生常谈了,大家对于技术动向的跟踪并不紧密呀,呵呵……
贴段我自己的代码,是用来枚举机器中所有的winsock对象及其相关进程的,供参考。稍做修改可满足各种需要。
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#pragma comment(lib, "ws2_32.lib")
typedef struct _HandleInfo
{
USHORT wPid;
USHORT wCreatorBackTraceIndex;
BYTE objType;
BYTE handleAttibs;
USHORT handleOffset;
DWORD dwKeObject;
ULONG dwGrantedAccess;
}HANDLEINFO, *PHANDLEINFO;
int main(int argc, char* argv[])
{
WSADATA wd;
unsigned int ret = WSAStartup(0x0202, &wd);
typedef DWORD (WINAPI *PQuerySystemInformation)(DWORD, PBYTE, DWORD, PDWORD);
PQuerySystemInformation pQuerySystemInformation = (PQuerySystemInformation)GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwQuerySystemInformation");
if(pQuerySystemInformation == NULL)
{
MessageBox(NULL, "Can't find NtQuerySystemInformation int Ntdll.dll!", "Failed", 0);
return 1;
}
BYTE *buf = new BYTE[20];
PHANDLEINFO phandleinfo = NULL;
DWORD dwRetSize = 0;
DWORD dwNum = 0;
unsigned int i;
ret = pQuerySystemInformation(16, buf,20,&dwRetSize);
if(0 != ret)
{
if(dwRetSize > 0)
{
//dwNum = dwRetSize/sizeof(HANDLEINFO);
delete [] buf;
buf = new BYTE[dwRetSize];
ret = pQuerySystemInformation(16, buf, dwRetSize, &dwRetSize);
if(0 != ret)
{
printf("Can't get any handles!\n");
goto end;
}
}
else
{
goto end;
}
}
dwNum = *(DWORD*)buf;
phandleinfo = (PHANDLEINFO)(buf+4);
for(i=0;i<dwNum;i++)
{
//static int iCount = 0;
//static WORD wPid = -1;
HANDLEINFO *pSeek = phandleinfo + i;
if((pSeek->objType==0x1a) && (pSeek->wPid))
{
//iCount++;
//wPid = pSeek->wPid;
HANDLE hSrcProcess;
hSrcProcess = OpenProcess(PROCESS_ALL_ACCESS,TRUE, pSeek->wPid);
if(hSrcProcess == NULL)
continue;
__try
{
SOCKET hSock;
ret = DuplicateHandle(hSrcProcess, (HANDLE)(pSeek->handleOffset), GetCurrentProcess(), (HANDLE *)&hSock, STANDARD_RIGHTS_REQUIRED,TRUE,0);
if(ret == 0)
{
int errcode = GetLastError();
continue;
}
sockaddr_in in = {0};
in.sin_family = AF_INET;
int dwSize = sizeof(in);
if(SOCKET_ERROR != getsockname(hSock, (sockaddr *)&in, &dwSize))
{
char name[0x100] = {0};
HMODULE hDll = LoadLibrary("psapi.dll");
typedef DWORD (WINAPI *PGETMODULEFILENAMEEX)(HANDLE, HMODULE, LPTSTR, DWORD);
//typedef BOOL (WINAPI *PENUMPROCESSMODULES)(HANDLE, HMODULE*, DWORD, LPDWORD);
PGETMODULEFILENAMEEX pfunc = (PGETMODULEFILENAMEEX)GetProcAddress(hDll, "GetModuleFileNameExA");
//PENUMPROCESSMODULES penum = (PENUMPROCESSMODULES)GetProcAddress(hDll, "EnumProcessModules");
//DWORD dwCb, dwRet;
//HMODULE module[1000];
//ret = penum(hSrcProcess
pfunc(hSrcProcess, NULL, name, 0x100);
FreeLibrary(hDll);
printf("socket:%4d port:%4d PID:%4d(%s)\n", pSeek->handleOffset, ntohs(in.sin_port), pSeek->wPid, name);
}
}
__finally
{
CloseHandle(hSrcProcess);
}
}
}
getchar();
end:
delete [] buf;
return 0;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hwman/archive/2005/01/14/254120.aspx