user2298581
user2298581

Reputation: 672

sending more than 65536 byte with TCP applications

I would like to know, how can two easy programs that transfer a text file from the sender to the receiver, send more than 65536 Byte (the maximum size of an IP packet). This is the sender:

 FILE *fp=fopen("file_to_send.txt","r");
 char msg[65536];
 len = strlen(msg)+1;
 nwrite=0;
 printf ("write()\n");
 fflush(stdout);
 do{
   n=write(socketfd, &(msg[nwrite]), len-nwrite);
   nwrite+=n;
 }
 while( (n<0) && (errno==EINTR) );

and this is the receiver:

#define MAXSIZE 65536
.....
char buf[MAXSIZE];
nread=0;
do{ 
  n=read(socketfd, &(buf[nread]), MAXSIZE ) ;
  fflush(stdout);
  nread+=n;
}while( (n<0) && (errno==EINTR) );

It works if file_to_send weight is < than 65536 but if it's bigger I lose parts of the text. Sorry for my bad English.

Upvotes: 0

Views: 2317

Answers (2)

pmoleri
pmoleri

Reputation: 4451

What's MAXSIZE?

In the receiver you are receiving MAXSIZE that could be bigger than the buffer itself.

You should be transfering the buffer to stdout in every loop, that way you always have space in the buffer for the next read.

char buf[65536];
nread=0;
do{ 
  n=read(socketfd, buf, 65536);
  if (n > 0) {
    n=write(stdout, buf, n);
    fflush(stdout);
    nread+=n;
  }
} while( (n>0) || (errno==EINTR) );

Also check Davide Berra 's answer to fix the loop condition in both sender and receiver.

Upvotes: 1

Davide Berra
Davide Berra

Reputation: 6568

You got a problem with the while control.

If write function is successful, it will return a value greater than 0, then your loop will exit after the first write.

Roughly, you should change this line

 while( (n<0) && (errno==EINTR) );

with

 while( n>0 || error==EINTR );

...and the same for the read side

Upvotes: 0

Related Questions