Reputation: 453
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?
Upvotes: 2
Views: 16174
Reputation: 37606
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
and use int32_t
or whatever is necessary for you.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]);
}
Upvotes: 3
Reputation: 368
You don't have to convert it.
For example, you can do :
int array[42];
write(sock, array, sizeof(array));
Upvotes: 0