Cryptography Reference
In-Depth Information
Listing 1-18: “webserver.c” remote connection exclusion code
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons( HTTP_PORT );
local_addr.sin_addr.s_addr = htonl( INADDR_LOOPBACK );
//local_addr.sin_addr.s_addr = htonl( INADDR_ANY );
if ( bind( listen_sock, ( struct sockaddr * ) &local_addr,
sizeof( local_addr ) ) == -1 )
If you uncomment the line below ( INADDR_ANY ), or just omit the setting of
local_addr.sin_addr.s_addr entirely, you accept connections from any avail-
able interface, including the one connected to the public Internet. In this case,
as a minor security precaution, disable this and only listen on the loopback
interface. If you have local fi rewall software running, this is unnecessary, but
just in case you don't, you should be aware of the security implications.
Now for the HTTP-specifi c parts of this server. Call process_http_request for
each received connection. Technically, you ought to spawn a new thread here so
that the main thread can cycle back around and accept new connections; however,
for the current purpose, this bare-bones single-threaded server is good enough.
Processing an HTTP request involves fi rst reading the request line that should
be of the format
GET < path > HTTP/1. x
Of course, HTTP supports additional commands such as POST , HEAD , PUT ,
DELETE , and OPTIONS , but you won't bother with any of those — GET is good
enough. If a client asks for any other functionality, return an error code 501:
Not Implemented. Otherwise, ignore the path requested and return a canned
HTML response as shown in Listing 1-19.
Listing 1-19: “webserver.c” process_http_request
static void process_http_request( int connection )
{
char *request_line;
request_line = read_line( connection );
if ( strncmp( request_line, “GET”, 3 ) )
{
// Only supports “GET” requests
build_error_response( connection, 501 );
}
else
{
// Skip over all header lines, don't care
while ( strcmp( read_line( connection ), “” ) );
build_success_response( connection );
}
#ifdef WIN32
Search WWH ::




Custom Search