I am writing an UDP-based streaming server and encountered a strange problem, I am sure it's just a simple error, but I cannot find a solution. The server does something along the lines of:
FILE* infile = fopen(inf, "rb");
register int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
int16_t buffer[LENGTH+HEADER];
struct header header;
int16_t data[LENGTH];
uint32_t number = 0;
/*set socket options etc. */
while(!feof(infile)){
fread(data, 1, LENGTH, infile);
/* if i write the contents of data to a file here, the error below occurs*/
fwrite(data, 1, LENGTH, testfile);
/*create a header, encode everything with htons/htonl*/
if(sendto(sock, buffer, LENGTH+HEADER, 0, (struct sockaddr*) &to,
sizeof to) < 0)
/*die*/
}
This seems to work. I can decode it and the data is not corrupt. However, I wrote a test client that works(or rather: does not work) as follows:
struct sockaddr_in si_other, si_me;
register int s;
unsigned int slen = sizeof(si_other);
int16_t buf[LENGTH+HEADER];
int16_t data[LENGTH];
FILE* file = fopen(of, "wb");
/*open socket, set options, etc. */
while(1){
if(recvfrom(s, (char *)buf, LENGTH+HEADER, 0, (struct sockaddr*) &si_other,
&slen) < 0)
/*die*/
decode(buf, data);
/* If I write the decoded data to a file here, the error below occurs */
fwrite(data, 1, LENGTH, testfile);
if(is_empty(data) == 0){
printf("End signal received.\n");
break;
}
}
Now to my problem. When I inspect the test files in hex with diff <(xxd test_before) <(xxd test_after)
, I get this(example diff line):
< 03d5ff0: f3fd f3fd 99fe 99fe 40ff 40ff e7ff e7ff ........@.@.....
---
> 03d5ff0: f3fd f3fd 0000 0000 0000 0000 0000 0000 ................
Which means that the last 12 bytes of the packets' data are lost. Everything else is fine.
This is only test code, so it is not as important(I guess), but it is weird and I want to know why.
Any ideas?
EDIT:
I have now tried a few approaches from the answers, thus far without getting anywhere. I will keep trying.
EDIT 2:
The code works on a different machine. I am not sure what the problem was, but it seems to work for anyone but me. Sorry for stealing your time and thank you for all the kind suggestions on how to improve the code and such!
Thanks in advance, Carson