如何在C中通过udp socket发送整数数组? [英] How to send integer array over udp socket in C?
本文介绍了如何在C中通过udp socket发送整数数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须通过udp套接字发送一个int数组。我是否必须将其转换为字符数组或字节序列?什么是标准解决方案?
I have to send an int array over an udp socket. Do I have to convert it as char array or as a sequence of byte? What is the standard solution?
推荐答案
您可以按照以下步骤操作:
You could just do as follow:
int array[100] ;
sendto(sockfd, array, sizeof(array), 0, &addr, addrlen);
要在另一边收回你的数组(假设你总是发送相同大小的数组):
To recv your array the other side (assuming you always send array of the same size):
int array[100] ;
recvfrom(sockfd, array, sizeof(array), 0, &addr, &addrlen);
正如评论中所说,你必须小心发送/接收系统的架构包。如果您正在为标准计算机开发应用程序,如果您想确定,则不应该有任何问题:
As said in the comments, you have to be carefull about the architecture of the system which send / receive the packet. If you're developping an application for 'standard' computers, you should not have any problem, if you want to be sure:
- 使用固定大小的类型(包括
stdint.h
并使用int32_t
或者您需要的任何内容。 - 检查代码中的字典。
- Use a fixed-size type (include
stdint.h
and useint32_t
or whatever is necessary for you. - Check for endianess in your code.
Endianess转换:
Endianess conversion:
// SENDER
int32_t array[100] = ... ;
int32_t arrayToSend[100] ;
for (int i = 0 ; i < 100 ; ++i) {
arrayToSend[i] = htonl(array[i]) ;
}
sendto(sockfd, arrayToSend, sizeof(arrayToSend), 0, &addr, addrlen);
// RECEIVER
int32_t array[100] ;
int32_t arrayReceived[100] ;
recvfrom(sockfd, arrayReceived, sizeof(arrayReceived), 0, &addr, &addrlen);
for (int i = 0 ; i < 100 ; ++i) {
array[i] = ntohl(arrayReceived[i]) ;
}
这篇关于如何在C中通过udp socket发送整数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文