A tiny HTTP client

connect

Syscall 42 (connect) takes the socket, a sockaddr_in with the server address and port, and its length. The port goes in network byte order: swap the bytes with a shift, or let the assembler do it:

%define SYS_CONNECT 42 mov rax, SYS_CONNECT mov rdi, fd mov rsi, server_addr mov rdx, 16 syscall

send the GET

Write the request bytes with sys_write on the connected socket. A minimal HTTP/1.0 GET ends with two CRLF pairs, and the server closes the connection when the response is done:

section .data request db "GET / HTTP/1.0", 13, 10, 13, 10 reqlen equ $ - request

Read the response

Read with sys_read into a buffer in a loop until it returns zero. The response is headers, a blank line, then the body - split on the first double CRLF if you only want the body.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which syscall number connects a socket on x86-64 Linux?

    Answer

    42

    socket is 41, connect is 42, accept is 43 and bind is 49.

  2. Why must the port be in network byte order?

    Answer

    The protocol sends the high byte first

    Network byte order is big-endian, while x86 stores the port little-endian.

  3. How does an HTTP/1.0 GET request end?

    Answer

    With two CRLF pairs

    The request line and each header end in CRLF, and an empty line closes the headers.

  4. Why does HTTP/1.0 let the client read until the socket closes?

    Answer

    The response length comes from the close, not a keep-alive

    Without keep-alive, the close of the connection marks the end of the response.

  5. What does read return when the response is complete and the peer closed?

    Answer

    0

    Zero bytes read is end of file, which ends the read loop.

  6. Where does the body start in an HTTP response?

    Answer

    After the first empty line

    Headers end with a blank line, and the body follows it.

  7. Which register points at the sockaddr_in for connect?

    Answer

    RSI

    RDI is the descriptor, RSI the address structure and RDX its length.

  8. What does the request buffer in this lesson hold?

    Answer

    GET / HTTP/1.0 and two CRLF pairs

    The minimal request asks for the root path with HTTP/1.0.

  9. How is the request sent on the connected socket?

    Answer

    With sys_write on the socket descriptor

    A connected socket is a descriptor, so write sends the bytes.

  10. Why is the output of this client not shown on the page?

    Answer

    The lesson was not run: it needs a network connection

    The container has no server to answer the request, so the page keeps its output unshown and says so.

The code on this page was not run: it needs a network connection. The snippets are fragments of a client, not whole programs.

Article author: Arthur Isaev