2012-03-13 91 views
1

我已經開始做一些基本的網絡編程。tcp/ip數據包偵聽器

我已經使用TcpClientTcpListener讀取/編寫了我自己的程序,而且工作正常。

但是,我正在使用的應用程序現在有點不同。

我想設置一個程序來偵聽tcp/ip數據包而無需連接。

例如,有一個數據包發送應用程序發送一個數據包到我的程序與適當的IP添加和端口號。

我也研究過使用Sharppcap和packet.net,但我發現的所有例子只偵聽本地找到的設備(沒有機會設置端口號和ip add等參數)。

有沒有人有關於如何去做這件事的建議?

+1

究竟是什麼你想在這裏解決什麼?目前尚不清楚問題是什麼。你說「沒有連接」,但不解釋你期望它不連接到什麼。您是否期望能夠以某種方式收聽遠程設備? – Oded 2012-03-13 19:23:44

+0

你看過UdpClient和UdpListner嗎? UDP是無連接協議。 – 2012-03-13 19:24:09

+0

@Oded,是的,我有一個設備正在傳輸ip/tcp數據包到我的程序。因此,與使用tcpclient/server時不存在與偵聽器的連接。我研究過Udp,我的問題是它不那麼可靠。我需要確保這些數據包能夠進入我的程序,而使用udp則沒有問題。 – Rick 2012-03-13 19:51:49

回答

2

你應該看看使用UDP協議而不是TCP/IP。

http://en.wikipedia.org/wiki/User_Datagram_Protocol

下面是客戶端的代碼:

using System.Net; 
using System.Net.Sockets; 

... 

/// <summary> 
/// Sends a sepcified number of UDP packets to a host or IP Address. 
/// </summary> 
/// <param name="hostNameOrAddress">The host name or an IP Address to which the UDP packets will be sent.</param> 
/// <param name="destinationPort">The destination port to which the UDP packets will be sent.</param> 
/// <param name="data">The data to send in the UDP packet.</param> 
/// <param name="count">The number of UDP packets to send.</param> 
public static void SendUDPPacket(string hostNameOrAddress, int destinationPort, string data, int count) 
{ 
    // Validate the destination port number 
    if (destinationPort < 1 || destinationPort > 65535) 
     throw new ArgumentOutOfRangeException("destinationPort", "Parameter destinationPort must be between 1 and 65,535."); 

    // Resolve the host name to an IP Address 
    IPAddress[] ipAddresses = Dns.GetHostAddresses(hostNameOrAddress); 
    if (ipAddresses.Length == 0) 
     throw new ArgumentException("Host name or address could not be resolved.", "hostNameOrAddress"); 

    // Use the first IP Address in the list 
    IPAddress destination = ipAddresses[0];    
    IPEndPoint endPoint = new IPEndPoint(destination, destinationPort); 
    byte[] buffer = Encoding.ASCII.GetBytes(data); 

    // Send the packets 
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);   
    for(int i = 0; i < count; i++) 
     socket.SendTo(buffer, endPoint); 
    socket.Close();    
} 
+0

這個問題被標記爲C#,而不是C,所以你的代碼示例不會對OP有幫助。 – Oded 2012-03-13 19:25:55

+0

我將語言更改爲C#@Oded – 2012-03-13 19:29:16

+1

您還應該查看此項目:http://www.codeproject.com/Articles/2614/Testing-TCP-and-UDP-socket-servers-using-C-和NET @ rick – 2012-03-13 19:30:07