How do I send an array of integers over TCP in C?

后端 未结 7 509
小蘑菇
小蘑菇 2020-12-17 06:39

I\'m lead to believe that write() can only send data buffers of byte (i.e. signed char), so how do I send an array of long integers using the C write()

7条回答
  •  -上瘾入骨i
    2020-12-17 07:42

    the prototype for write is:

    ssize_t write(int fd, const void *buf, size_t count);
    

    so while it writes in units of bytes, it can take a pointer of any type. Passing an int* will be no problem at all.

    EDIT:

    I would however, recomend that you also send the amount of integers you plan to send first so the reciever knows how much to read. Something like this (error checking omitted for brevity):

    int x[10] = { ... };
    int count = 10;
    write(sock, &count, sizeof(count));
    write(sock, x, sizeof(x));
    

    NOTE: if the array is from dynamic memory (like you malloced it), you cannot use sizeof on it. In this case count would be equal to: sizeof(int) * element_count

    EDIT:

    As Brian Mitchell noted, you will likely need to be careful of endian issues as well. This is the case when sending any multibyte value (as in the count I recommended as well as each element of the array). This is done with the: htons/htonl and ntohs/ntohl functions.

提交回复
热议问题