2012-02-22 66 views
-1

我想在c#中聽特定的端口,但我不想在網上寫一個聊天程序。 我只想聽一個端口並接收來自該端口的所有字節。 我之前問過這個問題,但我沒有得到有用的答案。我再說一遍,我不想有一個客戶端和服務器程序,我只想在我的計算機上運行一個程序,並向我顯示從特定端口接收到的字節數,或者向我顯示IP是什麼的程序連接到每個端口,如CMD中的「netstat」命令(我不想在我的C#程序中使用CMD命令) 請幫助我。聽特定的端口c#

+1

閱讀關於在C#中使用套接字。你所要做的就是在指定的端口上創建一個監聽套接字,並在數據進入時對數據做任何事情。你嘗試過什麼?你有沒有編寫任何代碼? StackOverflow可以幫助那些幫助他們的人;) – Kitsune 2012-02-22 21:44:55

+0

至於你的問題的最後部分 - 請查看這裏關於使用netstat後面的API的問題:http://stackoverflow.com/questions/9110211/how-to-check-who -use-certain-port-in-c/9110360#9110360 – 2012-02-22 21:46:32

+0

「之前我問過這個問題,但我沒有得到有用的答案」......發佈前面提到的問題的URL可能會有幫助 – tcarvin 2012-02-22 21:47:23

回答

3

我認爲這應該讓你開始。這將顯示您的類似信息netstat

using System; 
using System.Net; 
using System.Net.NetworkInformation; 

static void Main() 
{ 

    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); 
    TcpConnectionInformation[] tcpConnections = ipGlobalProperties.GetActiveTcpConnections(); 

    foreach (TcpConnectionInformation tcpConnection in tcpConnections) 
    { 
     Console.WriteLine("Local Address {0}:{1}\nForeign Address {2}:{3}\nState {4}", 
         tcpConnection.LocalEndPoint.Address, 
         tcpConnection.LocalEndPoint.Port, 
         tcpConnection.RemoteEndPoint.Address, 
         tcpConnection.RemoteEndPoint.Port, 
         tcpConnection.State); 
    } 
} 

要收聽端口,通過微軟here提供的示例代碼應該讓你去。

+0

@Mostafa你需要更多的細節來接受這個答案嗎? – 2012-03-03 06:48:17