Client http socket in c

Asked

Viewed 53 times

2

People would like someone to explain to me the following code snippet of an http client does, mainly this expression on while(sent < strlen(get)), the complete code is found at this link.

 int sent = 0;

  while(sent < strlen(get))

  {

    tmpres = send(sock, get+sent, strlen(get)-sent, 0);

    if(tmpres == -1){

      perror("Can't send query");

      exit(1);
    }

    sent += tmpres;

  }

1 answer

3


A call to ssize_t send(int sockfd, const void *buf, size_t len, int flags) sending at most len buffer bytes pointed by buf. It may send fewer bytes than the maximum. In this code, the variable sent account the number of bytes that have already been sent in the socket; while that number is less than the total number of bytes that need to be sent, the loop will continue to be executed.

For example, assuming the string get has 50 bytes. In the first loop iteration (error handling removed), suppose the socket sends only 30 bytes (instead of the 50 that are requested):

while(sent < strlen(get))  // sent = 0, strlen(get) = 50
{
    // o terceiro parâmetro - strlen(get)-sent - é igual a 50
    tmpres = send(sock, get+sent, strlen(get)-sent, 0);
    // assumindo que o socket enviou 30 bytes, tempres = 30
    sent += tmpres; // sent = 30
}

Now the third parameter of send is equal to 20. If in this second call the socket sends 20 bytes:

while(sent < strlen(get))  // sent = 30, strlen(get) = 50
{
    tmpres = send(sock, get+sent, strlen(get)-sent, 0);
    // assumindo que o socket enviou 20 bytes, tempres = 20
    sent += tmpres; // sent = 50
}

And with all bytes sent, the loop ends.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.