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?
-
Sending something over a UDP socker is never a problem. Receiving, on the other hand...n. m. could be an AI– n. m. could be an AI2014-05-27 15:48:17 +00:00Commented May 27, 2014 at 15:48
-
You have EVERYTHING here beej.us/guide/bgnet/output/html/singlepage/bgnet.htmlZach P– Zach P2014-05-27 15:54:01 +00:00Commented May 27, 2014 at 15:54
Add a comment
|
2 Answers
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:
- Use a fixed-size type (include
stdint.hand useint32_tor whatever is necessary for you. - Check for endianess in your code.
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]);
}
6 Comments
user3574984
how do I handle the packet on client side? If I use an int array it doesn't work!
n. m. could be an AI
Generally you don't. If you find yourself breaking your into packets, it usually means that UDP is not the right protocol for you.
user3574984
well, if I send something I usually also want to receive it. UDP is the right protocol, I just need to know how to receive a int array!
n. m. could be an AI
You know enough about protocols to decide which one is right for your application, but not enough to be able to send a chunk of data? Well maybe, who am I to doubt that... You send a part of the array, taking care not to straddle
int boundaries. Then the next part. Then the next part... The payload size of 512 bytes per packet is considered to work reliably over the Internet. If you are on an internal network, you might be able to get away with larger sizes like 8192.user3574984
I know how UDP and TCP work, the connection setup is too expensive, I can tollerate data loss and I send less than 512 bytes. I know how does it work, I don't know what is the standard to code it.
|