I'm writing a client/server based on udp and I want to send a sequence number along with with each datagram, I have tried to send the struct over udp using #pragma or pack structs with no luck.
typedef struct {
char buf[BUF_SIZE]; //buffer size is 4096
int seq;
} pack;
When I try to send a file with size 131094 bits, I receive the file at the other side with 135300 bits. my question is, is there a way to do it without Serialization?
n = recvfrom(sd,&pkt,sizeof(pkt),0,(struct sockaddr *)&clt,&l);
Here n
will be either -1 or the size of the entire received packet, including the sequence number word.
write(fd, pkt.buf,n)
Here n
is still the size of the entire received packet. You're not subtracting the size of the sequence number from the length of the packet, so you're writing extra bytes per write. You should be calling
write(fd, pkt.buf, n-sizeof int);
However it seems to me that the packets should also contain their own length, to cope with the case where the data isn't a multiple of 4096 bytes.