Cryptography Reference
In-Depth Information
( struct sockaddr * ) &client_addr,
&client_addr_len ) ) != -1 )
{
// TODO: ideally, this would spawn a new thread.
process_http_request( connect_sock );
}
if ( connect_sock == -1 )
{
perror( “Unable to accept socket” );
}
return 0;
}
This code is standard sockets fare. It issues the four required system calls
that are required for a process to act as a TCP protocol server:
socket
,
bind
,
listen
, and
accept
. The
accept
call will
block
— that is, not return — until a
client somewhere on the Internet calls
connect
with its IP and port number.
The inside of this
while
loop handles the request. Note that there's nothing
HTTP specifi c about this loop yet; this could just as easily be an e-mail server,
an ftp server, an IRC server, and so on. If anything goes wrong, these calls
return -1,
perror
prints out a description of what happened, and the process
terminates.
There are two points to note about this routine:
The call to
setsockopt( listen_socket, SOL_SOCKET, SO_REUSEADDR,
&on, sizeof( on ) )
. This enables the same process to be restarted if
it terminates abnormally. Ordinarily, when a server process terminates
abnormally, the socket is left open for a period of time referred to as the
TIME_WAIT
period. The socket is in
TIME_WAIT
state if you run
netstat
.
This enables any pending client
FIN
packets to be received and processed
correctly. Until this
TIME_WAIT
period has ended, no process can listen on
the same port.
SO_REUSEADDR
enables a process to take up ownership of a
socket that is in the
TIME_WAIT
state, so that on abnormal termination, the
process can be immediately restarted. This is probably what you always
want, but you have to ask for it explicitly.
Notice the arguments to
bind
. The
bind
system call tells the OS which port
you want to listen on and is, of course, required. However,
bind
accepts a
port as well as an interface name/IP address. By supplying an IP address
here, you can specify that you're only interested in connections coming
into a certain interface. You can take advantage of that and bind this socket
with the loopback address (127.0.0.1) to ensure that only connections from
this machine are accepted (see Listing 1-18).
Search WWH ::
Custom Search