i have following basic c++ code transferring file via udp using sockets on linux. problem is, not packets gets delivered (like 8 bytes out of 345kb received), know udp unreliable have code or because of udp's unreliability?
client side
sockfd=socket(af_inet,sock_dgram,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = af_inet; servaddr.sin_addr.s_addr=inet_addr("192.168.0.152"); servaddr.sin_port=htons(32000); ifstream myfile("345kb.doc", ios::in); int i=0; char* memblock; double size; if(myfile.is_open()) { myfile.seekg(0,ios::end); size=(double)myfile.tellg(); memblock=new char[1024]; myfile.seekg(0,ios::beg); double filesize=size; cout<<filesize; int n; int ab=(int)filesize%1024; while(filesize>1024){ myfile.read(memblock,1024); cout<<"\nread:"<<strlen(memblock)<<"\n"<<"sent:"; n=sendto(sockfd,memblock,strlen(memblock),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); filesize=filesize-1024; cout<<n<<"\n"; } myfile.read(memblock,1024); n=sendto(sockfd,memblock,strlen(memblock),0,(struct sockaddr *)&servaddr,sizeof(servaddr)); std::cout<<"hi"<<endl; } else { printf("\nfile not opened \n"); }
server side
int sockfd,n; struct sockaddr_in servaddr,cliaddr; socklen_t len; char mesg[1024]; sockfd=socket(af_inet,sock_dgram,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = af_inet; servaddr.sin_addr.s_addr=htonl(inaddr_any); servaddr.sin_port=htons(32000); bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)); //for (;;) //{ ofstream myfile; myfile.open("345kbsssss.doc",ios::out|ios::app); if(myfile.is_open()) { long i=0; len = sizeof(cliaddr); while((n = recvfrom(sockfd,mesg,1024,0,(struct sockaddr *)&cliaddr,&len))>0){ std::cout<<"hi\n"; //n=recvfrom(sockfd,mesg,256,0,(struct sockaddr *)&cliaddr,&len); myfile.write(mesg,n); } } else printf("\nfile not created\n"); //}
both true:
udp not meant used file transfer without implementing checking, reordering , retransmission. instead of implementing these on udp, better switch tcp. rare exception of resource limited embedded systems.
in code use
strlen
block length, since file (most probably) binary producing incorrect length values , not transmit whole file data.strlen
operates on 0 terminated strings , counts first 0 byte in data.
to more correct results, easiest way replace strlen(memblock)
min(1024,filesize)
. not perfect solution because not check how many bytes read myfile.read
.
Comments
Post a Comment