【问题标题】:tcp/ip packet listenertcp/ip 数据包监听器
【发布时间】:2012-03-30 05:45:25
【问题描述】:

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

我已经使用TcpClient 和TcpListener 读/写了我自己的程序,并且效果很好。

但是,我现在正在处理的应用程序的工作方式有所不同。

我想设置一个无需连接即可侦听 tcp/ip 数据包的程序。

例如,让一个数据包发送应用程序使用适当的 ip add 和端口号向我的程序发送一个数据包。

我也研究过使用 Sharppcap 和 packet.net,但我发现的所有示例都只侦听本地找到的设备(没有机会设置端口号和 ip add 等参数)。

有人对如何进行此操作有建议吗?

【问题讨论】:

  • 您到底想在这里解决什么问题?目前尚不清楚问题是什么。您说“无需连接”,但没有解释您希望它不连接的内容。您是否希望能够以某种方式收听远程设备?
  • 你看过 UdpClient 和 UdpListner 吗? UDP 是一种无连接协议。
  • @Oded,是的,我有一台设备正在向我的程序传输 ip/tcp 数据包。因此,不会像使用 tcpclient/server 那样连接到侦听器。我研究过 Udp,我的问题是它不那么可靠。我需要确保这些数据包到达我的程序并且使用 udp 没有 ack。
  • 设备是什么?只是好奇..

标签: c# network-programming sharppcap


【解决方案1】:

您应该考虑使用 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();            
}

【讨论】:

  • 问题被标记为 C#,而不是 C,因此您的代码示例对 OP 没有太大帮助。
  • 我将语言更改为 C# @Oded
  • 你也应该看看这个项目:codeproject.com/Articles/2614/…@rick
猜你喜欢
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 2016-10-03
相关资源
最近更新 更多