Search code examples
c#.netwindowspinvokenamed-pipes

Get process ID of a client that connected to a named pipe server with C#


I'm not sure if I'm just not seeing it, or what? I need to know the process ID of a client that connected via a named pipe to my server from an instance of NamedPipeServerStream. Is such possible?

In the meantime I came up with this function:

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out UInt32 ClientProcessId);
public static UInt32 getNamedPipeClientProcID(NamedPipeServerStream pipeServer)
{
    //RETURN:
    //      = Client process ID that connected via the named pipe to this server, or
    //      = 0 if error
    UInt32 nProcID = 0;
    try
    {
        IntPtr hPipe = pipeServer.SafePipeHandle.DangerousGetHandle();
        GetNamedPipeClientProcessId(hPipe, out nProcID);
    }
    catch
    {
        //Error
        nProcID = 0;
    }

    return nProcID;
}

I'm not very strong in "DangerousGetHandles" and "DllImports". I'm way better off with Win32, which I'm using here.


Solution

  • The main problem with that code, is that it does not perform correct error handling. You need to check the return value of GetNamedPipeClientProcessId to detect an error.

    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);
    public static uint getNamedPipeClientProcID(NamedPipeServerStream pipeServer)
    {
        UInt32 nProcID;
        IntPtr hPipe = pipeServer.SafePipeHandle.DangerousGetHandle();
        if (GetNamedPipeClientProcessId(hPipe, out nProcID))
            return nProcID;
        return 0;
    }