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

瘦欲@ 提交于 2019-12-06 14:11:21

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/15896315/get-process-id-of-a-client-that-connected-to-a-named-pipe-server-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!