Cryptography Reference
In-Depth Information
if ( closesocket( connection ) == -1 )
#else
if ( close( connection ) == -1 )
#endif
{
perror( “Unable to close connection” );
}
}
Because HTTP is line-oriented — that is, clients are expected to pass in
multiple CRLF-delimited lines that describe a request — you need a way to read
a line from the connection. fgets is a standard way to read a line of text from a
fi le descriptor, including a socket, but it requires that you specify a maximum
line-length up front. Instead, develop a simple (and simplistic) routine that
autoincrements an internal buffer until it's read the entire line and returns it
as shown in Listing 1-20.
Listing 1-20: “webserver.c” read_line
#define DEFAULT_LINE_LEN 255
char *read_line( int connection )
{
static int line_len = DEFAULT_LINE_LEN;
static char *line = NULL;
int size;
char c; // must be c, not int
int pos = 0;
if ( !line )
{
line = malloc( line_len );
}
while ( ( size = recv( connection, &c, 1, 0 ) ) > 0 )
{
if ( ( c == '\n' ) && ( line[ pos - 1 ] == '\r' ) )
{
line[ pos - 1 ] = '\0';
break;
}
line[ pos++ ] = c;
if ( pos > line_len )
{
line_len *= 2;
line = realloc( line, line_len );
}
}
return line;
}
 
Search WWH ::




Custom Search