This issue has always been discussed. We are not closely following technical trends ......
My own code is used to enumerate all Winsock objects and related processes on the machine for reference. Slight modifications can meet various needs.
# 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 = maid (0x0202, & WD );
Typedef DWORD (winapi * pquerysysteminformation) (DWORD, pbyte, DWORD, pdword );
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 = 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 * handle EK = phandleinfo + I;
If (effecek-> objtype = 0x1a) & (effecek-> wpid ))
{
// Icount ++;
// Wpid = pseek-> wpid;
Handle hsrcprocess;
Hsrcprocess = OpenProcess (process_all_access, true, javasek-> 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 = {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 [1, 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;
}