/* readcrlf.c - From Jon C. Snader: Effective TCP/IP Programming * Addison-Wesley 2000 * For better understanding, read the excellent Snader book. */ #include "etcp.h" /* readcrlf - read a CR/LN ("\r\n")terminated line (but accept it even if terminated with just '\n') from socket s into buffer buf of size len. The line is terminated with '\0' and does not include the terminating "\r\n" (or just '\n'). It returns the size of the line read, if successful, otherwise it returns a negative number. */ int readcrlf( SOCKET s, char *buf, size_t len ) { /* It reads one character at a time. */ char *bufx = buf; int rc; char c; char lastc = 0; while ( len > 0 ) { if ( ( rc = recv( s, &c, 1, 0 ) ) != 1 ) { /* * If we were interrupted, keep going, * otherwise, return EOF or the error. */ if ( rc < 0 && errno == EINTR ) continue; return rc; } if ( c == '\n' ) { if ( lastc == '\r' ) buf--; *buf = '\0'; /* don't include */ return buf - bufx; } *buf++ = c; lastc = c; len--; } set_errno( EMSGSIZE ); return -1; }