Networking in C · advanced · ~15 min

A tiny HTTP GET client

Send an HTTP/1.0 request over a TCP connection, then read and parse the response status line.

Lesson

How HTTP/1.0 works

HTTP/1.0 is a text-based protocol that runs on top of TCP. Because it is text, you can write a request as a plain string and read the reply the same way.

The exchange has three steps:

  1. Connect a TCP socket to the server.

  2. Write the request. A minimal GET request looks like this:

    GET /path HTTP/1.0\r\nHost: example\r\n\r\n
    

    Each line ends with \r\n (carriage return + line feed). The blank line at the end (an extra \r\n) tells the server the request is finished.

  3. Read the response from the same socket.

Stay on localhost

For the C-platform exercises, only target localhost. The test harness starts a local server in a separate thread for you to connect to.

Never point such a client at third-party hosts without explicit permission.

Code examples

const char *req = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n";
write(s, req, strlen(req));
char buf[4096]; ssize_t n = read(s, buf, sizeof buf - 1);
buf[n] = 0; puts(buf);

Summary

Key takeaways

  • HTTP/1.0 is a plain-text protocol carried over TCP.
  • A request is: connect, write GET /path HTTP/1.0 with \r\n line endings and a trailing blank line, then read the reply.
  • In these exercises, connect only to localhost (the harness runs a local test server).
  • Do not run the client against third-party hosts without permission.

Practice with these exercises