#include #include #include #include #include #define PORT 31337 #define OUT_FILE "junk" //#define HOST 192. //#define flen 53851 #define BUFLEN 65536 //65536-20 is the maximum udp packet size, looks like a nice maximum for server. /** * TODO: * Make sure data is fetched from same client. **/ int main(void){ int sockHandle; //int port; struct sockaddr_in *sock_server, *sock_client; char buf[BUFLEN]; unsigned int downloaded=0; unsigned int sequence=0; unsigned int fileSize=0; int packetCount=-1; int received=0; FILE *fileHandle; socklen_t socklen=sizeof(struct sockaddr_in); printf("datasink\n"); sock_server = malloc(socklen); sock_client = malloc(socklen); if(!sock_server || !sock_client){ printf("Cannot allocate memory for socket.\n"); } sockHandle=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(sockHandle<0){ printf("Cannot get socket\n"); return 0; } sock_server->sin_family = AF_INET; sock_server->sin_addr.s_addr=htonl(INADDR_ANY); sock_server->sin_port = htons(PORT); if(bind(sockHandle, (struct sockaddr *)sock_server, socklen)<0){ printf("Error, cannot bind socket\n"); return 0; } fileHandle=fopen(OUT_FILE, "wb"); if(fileHandle==NULL){ printf("Cannot open file for writing\n"); return 0; } printf("ready for data\n"); while(1){ received=recvfrom(sockHandle, buf, BUFLEN, 0, (struct sockaddr *)sock_client, &socklen); if(received<0){ printf("Error, cannot receive data\n"); return 0; } if(packetCount==-1){ sequence = buf[0]<<8; sequence |= buf[1]; sequence &= 0x0000ffff; if(sequence!=0){ printf("Caught packet in middle of stream, ignoring\n"); continue; }else{ printf("Caught first packet, starting capture.\n"); packetCount=0; fileSize = (buf[2] & 0x000000ff)<<8; fileSize |= buf[3] & 0x000000ff; fileSize &= 0x0000ffff; printf("File size is: %u\n", fileSize); fwrite(buf+4, 1, received-4, fileHandle); downloaded=received-4; } }else{ sequence = buf[0]<<8; sequence |= buf[1]; sequence &= 0x0000ffff; if(sequence!=packetCount+1){ printf("Missed a packet, bumping sequence. Expecting %u, got %u. Waiting for new sequence.\n", packetCount+1, sequence); fseek(fileHandle, 0, SEEK_SET); packetCount=0; downloaded=0; }else{ fwrite(buf+2, 1, received-2, fileHandle); packetCount++; downloaded += received-2; printf("Downloaded: %i\n", downloaded); } } if(downloaded>=fileSize){ printf("Download complete. %i out of %i bytes.\n", downloaded, fileSize); break; } } fclose(fileHandle); //listen(sockHandle) }