繁体   English   中英

如何构造 UDP 数据包但不发送

[英]How to construct UDP packet but not send it

这是一个奇怪的要求。

我有一个字节数组,我需要使用 C# 通过串行端口将其发送到另一个设备。 但是我需要首先将字节数组包装在 udp 数据包中,但同样,它将通过串行端口发送,而不是通过 udp。 有没有办法将 udp 数据包构造为字节数组,然后通过串口发送?

我以前使用 udp 发送和接收消息,但从来没有在构造 udp 数据包但未通过 udp 发送的位置发送和接收消息。

我将接受 Yochai 的回答,因为该链接(以及该站点内的其他页面)提供了构建 udp 数据包和 ip Z099FB995346F31C749F6E40DB0F395EE3 的代码。 对于其他试图完成它的人,这里是代码:

如何称呼它:

var udpPacketBytes = UDPPacket.Construct(IPAddress.Parse("1.1.1.1"), 1000, IPAddress.Parse("2.2.2.2"), 6100, payloadBytes);

UDP包class:

public static class UDPPacket
    {
        public static byte[] Construct(IPAddress sourceAddress, ushort sourcePort, IPAddress destinationAddress, ushort destinationPort, byte[] payload)
        {
            var bindAddress = IPAddress.Any;

            // Make sure parameters are consistent
            //if ((sourceAddress.AddressFamily != destinationAddress.AddressFamily) || (sourceAddress.AddressFamily != bindAddress.AddressFamily))
            //{
            //    throw new Exception("Source and destination address families don't match!");
            //}

            // Start building the headers
            byte[] builtPacket;
            UdpHeader udpPacket = new UdpHeader();
            ArrayList headerList = new ArrayList();
            //Socket rawSocket = null;
            //SocketOptionLevel socketLevel = SocketOptionLevel.IP;

            // Fill out the UDP header first
            Console.WriteLine("Filling out the UDP header...");
            udpPacket.SourcePort = sourcePort;
            udpPacket.DestinationPort = destinationPort;
            udpPacket.Length = (ushort)(UdpHeader.UdpHeaderLength + payload.Length);
            udpPacket.Checksum = 0;

            if (sourceAddress.AddressFamily == AddressFamily.InterNetwork)
            {
                Ipv4Header ipv4Packet = new Ipv4Header();

                // Build the IPv4 header
                Console.WriteLine("Building the IPv4 header...");
                ipv4Packet.Version = 4;
                ipv4Packet.Protocol = (byte)ProtocolType.Udp;
                ipv4Packet.Ttl = 2;
                ipv4Packet.Offset = 0;
                ipv4Packet.Length = (byte)Ipv4Header.Ipv4HeaderLength;
                ipv4Packet.TotalLength = (ushort)System.Convert.ToUInt16(Ipv4Header.Ipv4HeaderLength + UdpHeader.UdpHeaderLength + payload.Length);
                ipv4Packet.SourceAddress = sourceAddress;
                ipv4Packet.DestinationAddress = destinationAddress;

                // Set the IPv4 header in the UDP header since it is required to calculate the
                //    pseudo header checksum
                Console.WriteLine("Setting the IPv4 header for pseudo header checksum...");
                udpPacket.ipv4PacketHeader = ipv4Packet;

                // Add IPv4 header to list of headers -- headers should be added in th order
                //    they appear in the packet (i.e. IP first then UDP)
                Console.WriteLine("Adding the IPv4 header to the list of header, encapsulating packet...");
                headerList.Add(ipv4Packet);
                //socketLevel = SocketOptionLevel.IP;
            }
            else if (sourceAddress.AddressFamily == AddressFamily.InterNetworkV6)
            {
                Ipv6Header ipv6Packet = new Ipv6Header();

                // Build the IPv6 header
                Console.WriteLine("Building the IPv6 header...");
                ipv6Packet.Version = 6;
                ipv6Packet.TrafficClass = 1;
                ipv6Packet.Flow = 2;
                ipv6Packet.HopLimit = 2;
                ipv6Packet.NextHeader = (byte)ProtocolType.Udp;
                ipv6Packet.PayloadLength = (ushort)(UdpHeader.UdpHeaderLength + payload.Length);
                ipv6Packet.SourceAddress = sourceAddress;
                ipv6Packet.DestinationAddress = destinationAddress;

                // Set the IPv6 header in the UDP header since it is required to calculate the
                //    pseudo header checksum
                Console.WriteLine("Setting the IPv6 header for pseudo header checksum...");
                udpPacket.ipv6PacketHeader = ipv6Packet;

                // Add the IPv6 header to the list of headers - headers should be added in the order
                //    they appear in the packet (i.e. IP first then UDP)
                Console.WriteLine("Adding the IPv6 header to the list of header, encapsulating packet...");
                headerList.Add(ipv6Packet);
                //socketLevel = SocketOptionLevel.IPv6;
            }

            // Add the UDP header to list of headers after the IP header has been added
            Console.WriteLine("Adding the UDP header to the list of header, after IP header...");
            headerList.Add(udpPacket);

            // Convert the header classes into the binary on-the-wire representation
            Console.WriteLine("Converting the header classes into the binary...");
            builtPacket = udpPacket.BuildPacket(headerList, payload);

            /*
            // Create the raw socket for this packet
            Console.WriteLine("Creating the raw socket using Socket()...");
            rawSocket = new Socket(sourceAddress.AddressFamily, SocketType.Raw, ProtocolType.Udp);

            // Bind the socket to the interface specified
            Console.WriteLine("Binding the socket to the specified interface using Bind()...");
            rawSocket.Bind(new IPEndPoint(bindAddress, 0));

            // Set the HeaderIncluded option since we include the IP header
            Console.WriteLine("Setting the HeaderIncluded option for IP header...");
            rawSocket.SetSocketOption(socketLevel, SocketOptionName.HeaderIncluded, 1);

            try
            {
                // Send the packet!
                Console.WriteLine("Sending the packet...");
                int rc = rawSocket.SendTo(builtPacket, new IPEndPoint(destinationAddress, destinationPort));
                Console.WriteLine("send {0} bytes to {1}", rc, destinationAddress.ToString());
            }
            catch (SocketException err)
            {
                Console.WriteLine("Socket error occurred: {0}", err.Message);
                // http://msdn.microsoft.com/en-us/library/ms740668.aspx
            }
            finally
            {
                // Close the socket
                Console.WriteLine("Closing the socket...");
                rawSocket.Close();
            }
            */

            return builtPacket;
        }
    }

协议类:(此处发布太长)

协议 Class 代码

您应该通过创建一个包含标准 UDP class 的 UDP class 来构建您的 UDP 数据包,该数据包包含标准 ZF5EF036B4D8B69FFE234 数据包中包含的所有数据。

数据如下

源端口 [SP](16 位) :当尝试连接或进行连接时,它指定本地机器等待侦听来自目标机器的响应的端口。

目标端口 [DP](16 位) :当用户希望连接到远程机器上的服务时,应用层程序指定初始连接应使用的端口。 当不作为初始连接的一部分时,这指定了在将数据包发送到其目的地时远程机器将使用哪个端口号。

长度 [Len](16 位) :这允许接收站知道有多少输入位应该是有效数据包的一部分。 长度是计算有多少字节是 UDP 数据包的一部分,包括 header 中的字节。 由于 UDP 在 header 中始终有 4 个字段,每个字段有 16 位,并且数据/有效负载长度可变,我们知道长度将为 8 +(有效负载中的字节数)。

UDP Checksum [UDPCS] (16 bits) :This is a checksum that covers the header and data portion of a UDP packet to allow the receiving host to verify the integrity of an incoming UDP packet. UDP 数据包在校验和字段中加载了预定义的数字,然后在计算校验和时,将校验和覆盖先前的值。 当数据包到达目的地时,目标机器的操作系统会查看 4 header 字段(从第 16 位到第 31 位组成的字节)并将它们从数据包中取出,然后重新计算数据包上的校验和,校验和字段中没有任何内容. 然后操作系统将计算的校验和与数据包中传输的校验和进行比较。 如果校验和相同,则数据正常,允许通过,但如果有差异,则UDP数据包,数据被丢弃,接收机器不尝试获取新的复制,并且发送机器不会尝试发送相同的数据包。 数据包永远丢失。 UDP 不可靠。 有关可靠的传输层 TCP/IP 套件协议,请参阅 TCP 数据包。

数据(可变位) :如您所料,这是 UDP 数据包的有效负载或数据部分。 有效负载可以是任意数量的协议(通常是应用层)。一些最常用的 UDP 协议包括 NFS、DNS 以及多种音频和视频流协议。 如果 UDP 数据包中发生错误并且需要修复错误,则由应用层查找错误并请求其应用层“大块”或“块”数据。

制作一个 class 来保存所有这些数据并适当地填充它,重载ToString以允许您然后转换为 Byte 数组。

希望这可以帮助。

我想我在 .NET 的UdpClient中看不到任何实际数据包级类的原因是因为坦率地说它很简单,因为它是一个无连接/无状态协议。

数据包格式非常简单

bits             0 – 15                   16 – 31
        +-----------------------+-------------------------+
0       | Source Port Number    | Destination Port Number |
        +-----------------------+-------------------------+
32      | Length                | Checksum                |
        +-----------------------+-------------------------+
64      |                                                 |
        |                      Data                       |
        |                                                 |
        +-------------------------------------------------+

另外,请注意校验和计算实际上确实有点复杂

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM