I'm programming in C.
Suppose that I receive a datagram with Berkely socket UDP. I receive 20 bytes. So I have a char buffer[20] where I can memorize this data.
Now I want to use the first 4 bytes as an int and the other as a char.
int varnumber;
memset(buffer,0x0, 20);
recvfrom(sd, buffer, 20, 0, (struct sockaddr *)Addr, &Len);
So if I want put into "varnumber" I have written this code:
varnumber=*((int *)&(buffer[0]));
This way is correct? If it isn't how can I do this? I can't change the packet received from the socket.
P.S.
I send from a server this datagram in order. Every datagram has a counter in this 4 bytes. So for example, I have:
datagram1: 00000000 00000000 00000000 000000001 ...(other char)...
datagram2: 00000000 00000000 00000000 000000010 ...(other char)...
ecc...
I tried to printf varnumber
for a lot of datagrams received. I read the numbers all in perfect order, but from 93 onwards I read jumps straight to number 1001.
I tried to see these packets on Wireshark and Wireshark doesn't show any problem, in fact If I visualize the counter in the datagram in the time order I see the correct order. My c program doesn't read 93 but read 1001. I don't know why.
I know that UDP does not guarantee the order, but I'm in localhost and this is so strange. It is also a problem that I always see, it is not occasional.