Connaitre le process connecté à vos socket

0/5 (3 avis)

Snippet vu 7 300 fois - Téléchargée 19 fois

Contenu du snippet

Permet de récupérer une instance de Process désignant l'application connecté à l'autre bout de vos Socket TCP.

Compatible avec Windows Xp Sp2 à Windows 7 (et +, certainement).

Source / Exemple :


[DllImport("iphlpapi.dll", SetLastError = true)]
static extern uint GetExtendedTcpTable(IntPtr pTcpTable, ref int dwOutBufLen, bool sort, int ipVersion, int tblClass, int reserved);

[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPROW_OWNER_PID {
    public uint state;
    public uint localAddr;
    public int localPort;
    public uint remoteAddr;
    public int remotePort;
    public int owningPid;
}
[StructLayout(LayoutKind.Sequential)]
public struct MIB_TCPTABLE_OWNER_PID {
    public uint dwNumEntries;
    MIB_TCPROW_OWNER_PID table;
}
private Process SocketOwningProcess(Socket Sck) {
    const int AF_INET = 2;
    const int TCP_TABLE_OWNER_PID_CONNECTIONS = 4;
    int buffSize = 0;
    Process ret = null;
    int port = ((IPEndPoint)Sck.RemoteEndPoint).Port;
    port = ((port & 0xFF00) >> 8) + ((port & 0x00FF) << 8);

    GetExtendedTcpTable(IntPtr.Zero, ref buffSize, true, AF_INET, TCP_TABLE_OWNER_PID_CONNECTIONS, 0);
    IntPtr buffTable = Marshal.AllocHGlobal(buffSize);
    try {
        if (0 != GetExtendedTcpTable(buffTable, ref buffSize, true, AF_INET, TCP_TABLE_OWNER_PID_CONNECTIONS, 0))
            return null;
        MIB_TCPTABLE_OWNER_PID tab = (MIB_TCPTABLE_OWNER_PID)Marshal.PtrToStructure(buffTable, typeof(MIB_TCPTABLE_OWNER_PID));
        IntPtr rowPtr = (IntPtr)((long)buffTable + Marshal.SizeOf(tab.dwNumEntries));

        for (int i = 0; i < tab.dwNumEntries; i++) {
            MIB_TCPROW_OWNER_PID tcpRow = (MIB_TCPROW_OWNER_PID)Marshal.PtrToStructure(rowPtr, typeof(MIB_TCPROW_OWNER_PID));
            if (tcpRow.localPort == port) {
                ret = Process.GetProcessById(tcpRow.owningPid);
                break;
            }
            rowPtr = (IntPtr)((long)rowPtr + Marshal.SizeOf(tcpRow));   // next entry
        }

    }
    finally {
        Marshal.FreeHGlobal(buffTable);
    }
    return ret;
}

Conclusion :


l'API équivalente pour les Socket UDP existe, je n'en avait pas besoin...

code inspiré de
http://www.codeguru.com/forum/archive/index.ph p/t-188092.html

ainsi que de ma source VB6:
http://www.vbfrance.com/codes/ENUMERATION-PORTS-TCP-IDENTIFCATION-PROCESS-PID-CONCERNE_53020.aspx

Puis refondu, pour être compatible avec Windows 7 et >

A voir également

Ajouter un commentaire Commentaires
cs_coq Messages postés 6351 Date d'inscription samedi 1 juin 2002 Statut Membre Dernière intervention 2 août 2014 101
1 avril 2011 à 23:56
Tiens justement j'ai lu un truc sur le même sujet il y a peu : http://blogs.msdn.com/b/fiddler/archive/2011/03/09/mapping-socket-or-port-to-owner-process-in-c-sharp-dotnet.aspx

Pour la partie fermeture c'était probablement en utilisant SetTcpEntry (http://msdn.microsoft.com/en-us/library/aa366378.aspx).
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 75
1 avril 2011 à 15:56
Merci pour l'info, ca n'augure rien de bon pour le passage prochain de nos postes sous Windows 7, au boulot.

faudra regarder des sources d'applis faisant un netstat sous Windows 7 ^^
TeBeCo Messages postés 467 Date d'inscription lundi 24 juin 2002 Statut Membre Dernière intervention 9 mars 2011
1 avril 2011 à 15:40
pour répondre a ta question sur la compatibilité ascendante :
Première API :

http://msdn.microsoft.com/en-us/library/aa365804(v=vs.85).aspx
End of client support : Windows XP
End of server support : Windows Server 2003

Note:
The AllocateAndGetTcpExTableFromStack function is deprecated and not supported on Windows Vista and later. On the Microsoft Windows Software Development Kit (SDK) released for Windows Vista and later, the function prototype for AllocateAndGetTcpExTableFromStack is still defined in the Iphlpapi.h header file for continued support on Windows Server 2003 and Windows XP.

J'ai déjà fait tourner un équivalent sous Win7, avec une option pour aller jusqu’à clôturer le Socket à la demande (Admin / UAC ... requis), sauf que je retrouve plus ou j'ai mis ça ...

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.