简体   繁体   English

在每个片段上发送带有UDP头的片段数据报

[英]Sending fragmented datagram with UDP header on every fragment

I am working with an embedded box that must be able to communicate with traditional computers using UDP. 我正在使用一个嵌入式盒,该盒必须能够使用UDP与传统计算机进行通信。 When the box sends large UDP messages (that need to be fragmented), a UDP header is included for each fragment. 当该框发送较大的UDP消息(需要分段)时,每个片段都将包含一个UDP标头。 Thus if I want to a send a large datagram, it will be fragmented like this: 因此,如果我要发送一个大数据报,它将像这样碎片化:

[eth hdr][ip hdr][udp hdr][    data 1    ] /* first fragment */
[eth hdr][ip hdr][udp hdr][    data 2    ] /* second fragment */
[eth hdr][ip hdr][udp hdr][  data 3  ]     /* last fragment */

I understand that this is not customary, as usually the udp header would only be included in only the first ip packet of the fragmented message. 我知道这不是惯例,因为通常udp标头仅包含在分段消息的第一个ip数据包中。 However, this works perfectly for communicating with the other machines I need to talk to (ex. using recvfrom), so I have no reason to dig in and try to change it. 但是,这非常适合与我需要与之交谈的其他计算机进行通信(例如,使用recvfrom),因此我没有理由深入研究并尝试对其进行更改。

My issue, however, is in reading messages. 但是,我的问题是阅读邮件。 The box seems to expect fragmented udp datagrams to be sent to it in the same manner. 该框似乎希望以同样的方式将分段的udp数据报发送给它。 By this I mean that it expects every ipv4 fragment to have a udp header. 我的意思是,它期望每个ipv4片段都有一个udp标头。 Before trying to change this (it's a rather specialized and complicated platform) I would like to know if there is any way to configure sendto() or any other such function for sending udp messages in this format. 在尝试更改此代码(这是一个非常专业且复杂的平台)之前,我想知道是否有任何方法可以配置sendto()或任何其他此类函数来以这种格式发送udp消息。 I see when monitoring the traffic that those udp headers aren't present. 我在监视流量时看到那些udp标头不存在。

Thank you very much for the help. 非常感谢你的帮助。

No. Socket's don't work this way. 不,Socket的工作方式不是这样。 Just write your own sendto wrapper to manually fragment the frames across multiple UDP packets on whatever buffer size boundary you choose. 只需编写您自己的sendto包装器,即可在您选择的任何缓冲区大小边界上,将帧跨多个UDP数据包手动分段。 This will achieve the desired effect that you want. 这样可以达到所需的效果。

Sample code as follows: 示例代码如下:

ssize_t fragmented_sendto(int sockfd, const void *buf, size_t len, int flags,
           const struct sockaddr *dest_addr, socklen_t addrlen, size_t MAX_PACKET_SIZE)
{
    unsigned char* ptr = (unsigned char*) buf;

    size_t total = 0;

    while (total <= len)
    {
       size_t newsize = len - total;
       if (newsize > MAX_PACKET_SIZE)
       {
           newsize = MAX_PACKET_SIZE;
       }
       ssize_t result = sendto(sockfd, ptr, newsize, flags, dest_addr, addrlen);
       if (result < 0)
       {
          // handle error
          return -1;
       }
       else
       {
          total += result;
          ptr += result;
       }
    }
    return (ssize_t)total;
}

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

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