Connaitre le process connecté à vos socket

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

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.