2013-04-09 69 views
1

我不確定如果我只是沒有看到它或什麼?我需要知道從NamedPipeServerStream實例通過命名管道連接到我的服務器的客戶端的進程ID。這樣可能嗎?獲取使用C#連接到命名管道服務器的客戶端的進程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,我在這裏使用的方式更好。

+0

實際上你的問題是什麼? – ken2k 2013-04-09 08:04:52

+0

你想知道「這是正確的」嗎?或者是什麼? – Ben 2013-04-09 08:56:46

+0

我最關心的是他們所謂的「DangerousGetHandle」。 – c00000fd 2013-04-09 09:45:47

回答

1

該代碼的主要問題是它不執行正確的錯誤處理。您需要檢查返回值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; 
} 
+0

謝謝。但我認爲這是多餘的,因爲我在開始時將nProcID設置爲0。 – c00000fd 2013-04-09 09:44:56

+2

好吧,編譯器應該已經警告過你,在'try'之前賦值給'nProcID'的值從未被使用過。無論如何,Win32函數不會用異常來指示錯誤。他們通過其返回值發出錯誤信號。 – 2013-04-09 09:52:55

相關問題