How to read UDP packet with variable length in C

后端 未结 4 1394
天命终不由人
天命终不由人 2021-01-13 15:34

I\'m sending a C struct over UDP

struct packet{
    int numInt;
    int* intList; //malloc\'ed as (sizeof(int)*numInt)
}

It will be seriali

4条回答
  •  攒了一身酷
    2021-01-13 15:52

    You could pass MSG_PEEK to recvfrom to find out exactly how big the buffer needs to be. So just recvfrom a few bytes with MSG_PEEK to find numInt and then recvfrom the real thing (this time without MSG_PEEK).

    The standard says something about MSG_PEEK, but kernel.org spells it better:

    MSG_PEEK

    This flag causes the receive operation to return data from the beginning of the receive queue without removing that data from the queue. Thus, a subsequent receive call will return the same data.

    Obviously at some point you will start wondering if doubling the number of system calls to save memory is worth it. I think it isn't.

提交回复
热议问题