首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >tcp/ip数据包监听程序

tcp/ip数据包监听程序
EN

Stack Overflow用户
提问于 2012-03-14 03:17:14
回答 1查看 2.6K关注 0票数 1

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

我已经使用TcpClientTcpListener阅读/编写了我自己的程序,并且工作得很好。

然而,我正在开发的应用程序现在的工作方式有点不同。

我想设置一个无需连接就能监听tcp/ip数据包的程序。

例如,让一个数据包发送应用程序发送一个数据包到我的程序,并添加适当的ip地址和端口号。

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

有没有人有关于如何做这件事的建议?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-14 03:23:48

您应该考虑使用UDP协议,而不是TCP/IP。

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

以下是客户端的代码:

代码语言:javascript
复制
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();            
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9690572

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档