2

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?

2

2 Answers 2

3

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.h and use int32_t or 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]);
}
Sign up to request clarification or add additional context in comments.

6 Comments

how do I handle the packet on client side? If I use an int array it doesn't work!
Generally you don't. If you find yourself breaking your into packets, it usually means that UDP is not the right protocol for you.
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!
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.
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.
|
0

You don't have to convert it.

For example, you can do :

int array[42];

write(sock, array, sizeof(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.