0
/* This function accepts a socket FD and a ptr to a destination
 * buffer.  It will receive from the socket until the EOL byte
 * sequence in seen.  The EOL bytes are read from the socket, but
 * the destination buffer is terminated before these bytes.
 * Returns the size of the read line (without EOL bytes).
 */
int recv_line(int sockfd, unsigned char *dest_buffer) {
#define EOL "\r\n" // End-of-line byte sequence
#define EOL_SIZE 2
   unsigned char *ptr;
   int eol_matched = 0;

   ptr = dest_buffer;
   while(recv(sockfd, ptr, 1, 0) == 1) { // Read a single byte.
      if(*ptr == EOL[eol_matched]) { // Does this byte match terminator?
         eol_matched++;
         if(eol_matched == EOL_SIZE) { // If all bytes match terminator,
            *(ptr+1-EOL_SIZE) = '\0'; // terminate the string.
            return strlen(dest_buffer); // Return bytes received
         }
      } else {
         eol_matched = 0;
      }
      ptr++; // Increment the pointer to the next byter.
   }
   return 0; // Didn't find the end-of-line characters.
}

Hey guyz I have a problem in the following lines and am not understanding what's going on here please explain me!

while(recv(sockfd, ptr, 1, 0) == 1) { // Read a single byte.
      if(*ptr == EOL[eol_matched]) { // Does this byte match terminator?
         eol_matched++;
         if(eol_matched == EOL_SIZE) { // If all bytes match terminator,
            *(ptr+1-EOL_SIZE) = '\0'; // terminate the string.
            return strlen(dest_buffer); // Return bytes received
         }
2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by abhimanipal
0

In your scenario when ever the sender is sending some data, the last 2 chars will always be '\r' and the '\n'. So if I wanted to send ABC across the stream then I will send it across like this
"ABC\r\n"

In the receive function the code is reading the data bye by byte. Initially when the first byte is read, *ptr contains A. The code checks to see if A is equal to the \r. It is not, so it will read the next byte. B and then C are also not equal to \r. Then in the 4th read the *ptr will contain \r. So now the code reads another byte and checks if that byte equals \n. If it does then the code NULL terminates the data it has read. So when the buffer is returned from the receive function it contains ABC\0
Did this solve your question or do you have more doubts

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.