[英]Get process ID of a client that connected to a named pipe server with C#
我不确定是否只是没有看到它,还是什么? 我需要知道通过NamedPipeServerStream
实例通过命名管道连接到我的服务器的客户端的进程ID。 有可能吗?
在此期间,我想到了以下功能:
[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;
}
我在“ DangerousGetHandles”和“ DllImports”中不是很强。 我在这里使用Win32会更好。
该代码的主要问题在于,它无法执行正确的错误处理。 您需要检查GetNamedPipeClientProcessId
的返回值以检测错误。
[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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.