通过套接字发送任意长度的数组.字节序 [英] Sending the array of arbitrary length through a socket. Endianness
问题描述
我现在正在使用套接字编程,但是遇到了一个问题,我不知道该如何以可移植的方式解决. 任务很简单:我需要通过网络发送16个字节的数组,在客户端应用程序中接收它并进行解析.我知道,有像htonl,htons之类的函数,因此可以与uint16和uint32一起使用.但是,我应该如何处理比这更大的数据呢?
I'm fighting with socket programming now and I've encountered a problem, which I don't know how to solve in a portable way. The task is simple : I need to send the array of 16 bytes over the network, receive it in a client application and parse it. I know, there are functions like htonl, htons and so one to use with uint16 and uint32. But what should I do with the chunks of data greater than that?
谢谢.
推荐答案
您说的是16个字节的数组.那真的没有帮助.字节序仅对大于字节的内容重要.
You say an array of 16 bytes. That doesn't really help. Endianness only matters for things larger than a byte.
如果它确实是原始字节,则只需发送它们,您将收到相同的消息
If it's really raw bytes then just send them, you will receive them just the same
如果它确实是一个结构,则要发送它
If it's really a struct you want to send it
struct msg
{
int foo;
int bar;
.....
然后,您需要遍历缓冲区以提取所需的值.
Then you need to work through the buffer pulling that values you want.
发送时,您必须将数据包组装成标准顺序
When you send you must assemble a packet into a standard order
int off = 0;
*(int*)&buff[off] = htonl(foo);
off += sizeof(int);
*(int*)&buff[off] = htonl(bar);
...
收到时
int foo = ntohl((int)buff[off]);
off += sizeof(int);
int bar = ntohl((int)buff[off]);
....
我看到您想发送一个IPv6地址,它们始终按网络字节顺序-因此您可以将其原始流式传输.
I see you want to send an IPv6 address, they are always in network byte order - so you can just stream it raw.
这篇关于通过套接字发送任意长度的数组.字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!