如何在 C 中通过 TCP 发送整数数组? [英] How do I send an array of integers over TCP in C?

查看:54
本文介绍了如何在 C 中通过 TCP 发送整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为 write() 只能发送字节的数据缓冲区(即带符号的字符),那么如何使用 C write 发送长整数数组() sys/socket.h 库中的函数?

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() function in the sys/socket.h library?

显然我不能只是将 long 转换或转换为 char,因为任何超过 127 的数字都会出现格式错误.

Obviously I can't just cast or convert long to char, as any numbers over 127 would be malformed.

我看了一下问题,如何将整数数组分解为字节数组(像素编码),但无法理解 - 如果这是我正在寻找的内容,请有人把它稍微简化一下吗?

I took a look at the question, how to decompose integer array to a byte array (pixel codings), but couldn't understand it - please could someone dumb it down a little if this is what I'm looking for?

为什么从 TCP 套接字读取整数数组时会得到奇怪的结果?

推荐答案

write 的原型是:

the prototype for write is:

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

所以当它以字节为单位写入时,它可以采用任何类型的指针.传递一个 int* 完全没有问题.

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.

然而,我建议您还发送您计划首先发送的整数数量,以便接收者知道要读取多少.像这样(为简洁起见省略了错误检查):

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));

注意:如果数组来自动态内存(就像你malloc编辑过的那样),你不能在它上面使用sizeof.在这种情况下,计数将等于:sizeof(int) * element_count

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

作为 Brian Mitchell 指出,您可能还需要注意 endian 问题.发送任何多字节值时就是这种情况(如我推荐的计数以及数组的每个元素).这是通过 htons/htonlntohs/ntohl 函数完成的.

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.

这篇关于如何在 C 中通过 TCP 发送整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆