2011-09-22 32 views
0

我們有Windows服務將由安裝程序安裝。我們有一個選項允許用戶提供端口號並選擇服務是否必須在安裝完成時開始。我們正在檢查安裝程序本身以檢查端口是否打開/可用。檢查端口是否分配給任何程序或添加到防火牆中 - C#

TcpClient TcpScan = new TcpClient(); 
TcpScan.Connect("localhost", portno); 
if (TcpScan.Connected == true) 
{ 
    TcpScan.Close(); 
} 

我的問題是,如果用戶選擇的不是選項來啓動上安裝該服務,然後我們用相同的端口在同一臺機器上安裝另一個實例作爲第一個使用,那麼如果我們開始這兩個服務,然後其中一個服務將無法正常工作。

那麼有什麼辦法可以檢查用戶提供的端口是否已經存在於防火牆中,或者是否已經分配給其他一些Windows服務? (同時假設服務可以處於停止狀態)

回答

0

最後得到的答案做一些[R & d

string OP = @"C:\Windows\Temp\ExceptionList.txt"; 

ProcessStartInfo procStartInfo = null; 

string command = "netsh advfirewall firewall show rule name=all > " + OP; 
procStartInfo = new ProcessStartInfo("cmd", "/c " + command); 

procStartInfo.CreateNoWindow = true; 
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
proc.StartInfo = procStartInfo; 
proc.Start(); 
proc.WaitForExit(); 

if (File.Exists(OP)) 
{ 
    StreamReader SR = new StreamReader(OP); 
    string FileData = SR.ReadToEnd(); 
    SR.Close(); 

    //Logic to read the output and then fetch only records which are enabled and have LocalPort 
} 

輸出(ExceptionList.txt)文件包含此格式的數據

Rule Name:       NETTCP 
--------------------------------------------- 
Enabled:        Yes 
Direction:       In 
Profiles:        Domain 
Grouping:        
LocalIP:        Any 
RemoteIP:        Any 
Protocol:        TCP 
LocalPort:       8080 
RemotePort:       Any 
Edge traversal:      No 
Action:        Allow 
0

我覺得不行,因爲任何應用程序都可以在運行時打開一個端口。
可以(例如)使用Mutex,以避免在同一端口上的服務的多個實例(給互斥像String.Format(MyMutex_{0},my_port}的名稱。
你可以/應該檢查該端口是免費服務啓動過程中和關閉它優雅,如果它不是。

相關問題