0

I have been working on how to transfer an image using UDP in C, I have created a code that sometimes works, sometimes it doesn't. In what I think the issue is that sometimes the server receives more packages than writes. I know that I am trying to create the TCP, but that is what I am kind looking for, but not sure how to do it.

I think to fix it the client should send the buff of the img and only sends the second part when the server reply back to the client.

Here is the code:

Client:

while (!feof(p))
    {
            fread(*&c, 1, BLEN, p);
            sprintf(buf, "%s", *&c);
            temp=sendto(s,buf,BLEN, 0, (struct sockaddr *) &si_other, slen);
            //sleep(3);
            //printf("%d ",temp);
            if(temp < 0)
            {
                    fprintf(stderr,"sendto error.\n");
                    printf("erro");
                    exit(1);
            }
            i++;
    }

Server:

while(1){
    if(recvfrom(s, buf, BLEN, 0, (struct sockaddr *) &si_other, (unsigned int *) &slen)==-1){
        perror("recvfrom error.\n");
        exit(1);
    }
    //printf("%s ", &si_other);
    flagr[0] = buf[0];
    flagr[1] = buf[1];
    flagr[2] = buf[2];
    if (strcmp(flagr, flag) == 0 ){
            break;
    }
    fwrite(buf, 1, BLEN, pp);
    i++;
}
Guizinhobeback
  • 86
  • 1
  • 14

1 Answers1

2

UDP is a datagram protocol, meaning that each call to sendto sends one message. If that message is larger than an IP packet can hold, it will be fragmented across multiple IP datagrams. If any one of those fragments fails to arrive, the whole thing is dropped at the OS level.

The data needs to be sent in chunks of no more than about 1450 bytes. Then the receiving side will need to read each packet and, because UDP does not guarantee that data will arrive in order, you will need to reassemble them in the proper order.

That means each packet has to have a user-defined header which contains the sequence number so that the receiver knows what order to put them in.

You also need to worry about retransmissions, since UDP doesn't guarantee that a packet that is send is actually received.

There's a program I wrote called UFTP which does all of this. Take a look at the documentation and code to get an idea of what you need to do to implement reliable data transfer over UDP.

dbush
  • 205,898
  • 23
  • 218
  • 273