我已经开始做一些基本的网络编程。

我已经使用TcpClientTcpListener读/写了自己的程序,并且它已经工作了。

但是,我正在处理的应用程序现在有点不同。

我想设置一个侦听TCP / IP报文的程序,而无需连接。

例如,具有数据包发送应用程序将数据包发送到我的程序,使用相应的IP添加和端口号。

我还看了用Sharppcap和packet.net,但我发现的所有示例只侦听在本地找到的设备上(没有机会设置端口号和IP添加等参数)。

有人有什么建议如何去做这件事吗?

有帮助吗?

解决方案

您应该查看使用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();            
}
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top