Next: , Previous: , Up: Steps in Implementing an Insecure HTTP Client   [Index]


1.3.1.3 Implementing An HTTP GET Command Function

An HTTP ‘GET’ command is a simple, plaintext command. It starts with the three ASCII-encoded letters ‘G E T’, all in uppercase (HTTP is case sensitive), a space, the path to the document to be retrieved, another space, and the token ‘HTTP/1.0’ OR ‘HTTP/1.1’ depending on which version of the HTTP protocol the client understands.1

The ‘GET’ command itself is followed by a carriage-return/line-feed pair (0x0A 0x0D) and a colon-separated, CRLF-delimited list of headers that describe how the client wants the response to be returned. Only one header is required—the ‘Host’ header, which is required to support virtual hosting, the situation where severral hosts share one IP address or vice-versa. The ‘Connection’ header is not required, but in general you should send it to indicate to the client whether you want it to ‘Keep-Alive’ the connection—if you plan on requesting more documents on this same socket—or ‘Close’ it. if you omit the ‘Connection: Close’ header line the server keeps the socket open until the client closes it. If you’re just sending a single request and getting bakc a single response, it’s easier to let the server just close the connection when it’s done sending. The header list is teminated by an empty CRLF pair.

A minimal HTTP ‘GET’ command looks like this:

GET /index.html HTTP/1.1
Host: www.server.com
Connection: close

The code to format and submit a ‘GET’ command over an established socket is shown in Listing 1-6. Note that the input is the socket itself—the connection argument—the path of the document being requested, and the host (to build the host header).

/**
 * Format and send an HTTP get command. The return value will be 0 on
 * success, -1 on failure, with errno set appropriately. The caller
 * must then retrieve the response.
 */

int http_get( int connection, const char *path, const char *host )
{
  static char get_command[ MAX_GET_COMMAND ];

  sprintf( get_command, "GET /%s HTTP/1.1\r\n", path );
  if ( send( connection, get_command, strlen( get_command ), 0 ) == -1 )
  {
    return -1;
  }

  sprintf( get_command, "Host: %s\r\n", host );
  if ( send( connection, get_command, strlen( get_command ), 0 ) == -1 )
  {
    return -1;
  }

  sprintf( get_command, "Connection: close\r\n\r\n" );
  if ( send( connection, get_command, strlen( get_command ), 0 ) == -1 )
  {
    return -1;
  }

  return 0;
}

Listing 1.3: "http.c" http_get


Footnotes

(1)

At the time of this writing, there are only two versions of HTTP; the differences are immaterial to this book.


Next: , Previous: , Up: Steps in Implementing an Insecure HTTP Client   [Index]