关闭

WINDOWS下获得端口对应的进程名1

743人阅读 评论(0) 收藏 举报
 

#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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3766708次
    • 积分:60928
    • 等级:
    • 排名:第42名
    • 原创:1549篇
    • 转载:1252篇
    • 译文:0篇
    • 评论:459条
    最新评论