How to solve: sending UDP packet using Sendto() got “message too long”

后端 未结 3 610
执笔经年
执笔经年 2021-01-13 08:30

I want to use the sendto() API to send video and audio data through UDP packet. The sending buffer size I got using getsockopt() is 114688, however, sendto() returned -1 wh

相关标签:
3条回答
  • 2021-01-13 08:56

    Per @datenwolf's answer, you simply can't send more than 64k in a single UDP datagram, as that limit is implicit in the two-byte length field in the protocol.

    Furthermore, it's not actually a good idea to send even that much at once. You should limit your packets to the MTU on the path between the two ends (typically in the region of 1500 bytes or less) so that you don't get fragmentation in the IP layer.

    Fragmentation is bad - ok?

    0 讨论(0)
  • 2021-01-13 09:02

    Why not just call sendto several times, with an offset into the buffer?

    int sendto_bigbuffer(int sock, const void *buffer, const size_t buflen, int flags,
                         const struct sockaddr *dest_addr, socklen_t addrlen)
    {
        size_t sendlen = MIN(buflen, 1024);
        size_t remlen  = buflen;
        const void *curpos = buffer;
    
        while (remlen > 0)
        {
            ssize_t len = sendto(sock, curpos, sendlen, flags, dest_addr, addrlen);
            if (len == -1)
                return -1;
    
            curpos += len;
            remlen -= len;
            sendlen = MIN(remlen, 1024);
        }
    
        return buflen;
    }
    

    Something like the above function will send the buffer 1024 bytes at a time.

    0 讨论(0)
  • 2021-01-13 09:09

    You can not send messages (datagrams) larger than 2^16 65536 octets with UDP. The length field of a UDP packet is 16 bits. The buffer sizes you're requesting are not about the size for a packet, but how many octets the OS does buffer incoming and outgoing in total (spread over multiple packets). But a single packet can not get larger.

    0 讨论(0)
提交回复
热议问题