Skip to main content
Be Bitwise
CAssembly Equivalents of C Patterns

Building a Simple TCP Server in Assembly

In the C networking module you built TCP clients and servers using the socket API: socket, bind, listen, accept, send, recv. All of those are thin C library wrappers around Linux syscalls. In this lesson we'll build a working TCP server entirely in x86-64 assembly, calling the socket syscalls ourselves. About as deep as you can go short of writing a kernel module.

Socket Syscalls Overview

Networking in Linux uses these syscalls:

SyscallNumberPurpose
socket41Create a socket file descriptor
bind49Assign an address/port to a socket
listen50Mark a socket as accepting connections
accept43Wait for and accept a new connection
read/recv0/45Read data from a connected socket
write/send1/44Write data to a connected socket
close3Close a socket

A socket is just a file descriptor, same as a file. Once it's connected you can read and write to it as if it were a file on disk.

The sockaddr_in Structure

To bind a socket, we need a sockaddr_in structure. In C:

c
struct sockaddr_in {
sa_family_t sin_family; // AF_INET = 2 (2 bytes)
in_port_t sin_port; // Port in network byte order (2 bytes)
struct in_addr sin_addr; // IP address (4 bytes)
char sin_zero[8]; // Padding (8 bytes)
};
// Total: 16 bytes

In assembly we lay it out by hand:

asm
section .data
; sockaddr_in structure for binding to 0.0.0.0:8080
sockaddr:
dw 2 ; sin_family = AF_INET
dw 0x901F ; sin_port = htons(8080) = 0x1F90 -> 0x901F (byte-swapped)
dd 0 ; sin_addr = INADDR_ANY (0.0.0.0)
dq 0 ; sin_zero padding
sockaddr_len equ $ - sockaddr
Network Byte Order

Network protocols speak big-endian. x86 is little-endian. Port 8080 = 0x1F90, and network order wants the bytes 1F 90 in memory, so on x86 you store the swapped value 0x901F. That's exactly what htons() does in C — it swaps bytes. In assembly you either pre-compute the swapped value (as above) or fire off a bswap (or xchg al, ah for a 16-bit port).

Type a port and an address below and watch the 16 bytes change. Try 8080, then 80, then 257 (0x0101), the odd case where forgetting htons does no harm.

sockaddr_in builder

16 bytes, x86-64 Linux
Bytes in memory, offset 0 to 15
02001f90000000000000000000000000
sin_familyoffset 002 00AF_INET = 2, host byte order
sin_portoffset 21f 90network byte order (htons)
sin_addroffset 400 00 00 00network byte order
sin_zerooffset 800 00 00 00 00 00 00 00padding, must be zero

Port 8080 is 0x1F90. htons puts the high byte first: 1f 90. Stored without htons, x86 would write 90 1f and the kernel would read port 36895.

mov word  [rdi],     2
mov word  [rdi + 2], 0x901F
mov dword [rdi + 4], 0x00000000

Change the port or address. Hover a field to highlight its bytes.

The Complete TCP Server

A working echo server. Accepts connections, sends back whatever shows up:

asm
section .data
sockaddr:
dw 2 ; AF_INET
dw 0x901F ; htons(8080)
dd 0 ; INADDR_ANY
dq 0 ; padding
sockaddr_len equ 16
welcome_msg: db "Connected to assembly server!", 10
welcome_len equ $ - welcome_msg
listen_msg: db "Listening on port 8080...", 10
listen_len equ $ - listen_msg
section .bss
recv_buffer: resb 1024 ; Buffer for received data
server_fd: resq 1 ; Server socket fd
client_fd: resq 1 ; Client socket fd
; Constants
AF_INET equ 2
SOCK_STREAM equ 1
SOL_SOCKET equ 1
SO_REUSEADDR equ 2
section .text
global _start
_start:
; === Step 1: Create socket ===
; socket(AF_INET, SOCK_STREAM, 0)
mov rax, 41 ; syscall: socket
mov rdi, AF_INET ; domain: IPv4
mov rsi, SOCK_STREAM ; type: TCP
xor rdx, rdx ; protocol: 0 (auto)
syscall
test rax, rax
js .fatal_error
mov [rel server_fd], rax
; === Step 2: Set SO_REUSEADDR ===
; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))
mov rax, 54 ; syscall: setsockopt
mov rdi, [rel server_fd]
mov rsi, SOL_SOCKET
mov rdx, SO_REUSEADDR
push 1 ; optval = 1 (enable)
mov r10, rsp ; pointer to optval
mov r8, 4 ; optlen = sizeof(int)
syscall
pop rax ; Clean up the pushed value
; === Step 3: Bind to address ===
; bind(server_fd, &sockaddr, sizeof(sockaddr))
mov rax, 49 ; syscall: bind
mov rdi, [rel server_fd]
lea rsi, [rel sockaddr]
mov rdx, sockaddr_len
syscall
test rax, rax
js .fatal_error
; === Step 4: Listen ===
; listen(server_fd, backlog=5)
mov rax, 50 ; syscall: listen
mov rdi, [rel server_fd]
mov rsi, 5 ; backlog: max queued connections
syscall
test rax, rax
js .fatal_error
; Print "Listening..." message
mov rax, 1
mov rdi, 1
lea rsi, [rel listen_msg]
mov rdx, listen_len
syscall
.accept_loop:
; === Step 5: Accept a connection ===
; accept(server_fd, NULL, NULL)
mov rax, 43 ; syscall: accept
mov rdi, [rel server_fd]
xor rsi, rsi ; addr: NULL (don't care about client address)
xor rdx, rdx ; addrlen: NULL
syscall
test rax, rax
js .accept_loop ; On error, try again
mov [rel client_fd], rax
; Send welcome message
mov rax, 1 ; write (works on sockets too)
mov rdi, [rel client_fd]
lea rsi, [rel welcome_msg]
mov rdx, welcome_len
syscall
.echo_loop:
; === Step 6: Read from client ===
; read(client_fd, buffer, 1024)
mov rax, 0 ; syscall: read
mov rdi, [rel client_fd]
lea rsi, [rel recv_buffer]
mov rdx, 1024
syscall
test rax, rax
jle .client_done ; 0 = client disconnected, negative = error
; === Step 7: Echo back ===
; write(client_fd, buffer, bytes_read)
mov rdx, rax ; count = bytes read
mov rax, 1 ; syscall: write
mov rdi, [rel client_fd]
lea rsi, [rel recv_buffer]
syscall
jmp .echo_loop ; Continue echoing
.client_done:
; Close client socket
mov rax, 3 ; syscall: close
mov rdi, [rel client_fd]
syscall
jmp .accept_loop ; Wait for next client
.fatal_error:
mov rax, 60 ; syscall: exit
mov rdi, 1 ; exit code: 1
syscall

Comparing to the C Version

The equivalent C code:

c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
int optval = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(8080),
.sin_addr.s_addr = INADDR_ANY,
};
bind(server_fd, (struct sockaddr *)&addr, sizeof(addr));
listen(server_fd, 5);
printf("Listening on port 8080...\n");
while (1) {
int client_fd = accept(server_fd, NULL, NULL);
write(client_fd, "Connected!\n", 11);
char buffer[1024];
ssize_t n;
while ((n = read(client_fd, buffer, 1024)) > 0) {
write(client_fd, buffer, n);
}
close(client_fd);
}
}

The C version is about 25 lines of logic. The assembly is roughly 100. Yet the syscall sequences are almost identical. A compiler's output for this program would come out very close to what we wrote by hand.

What the C Socket Library Abstracts

Side by side, you can see exactly what the C library is giving you:

  1. htons() / ntohs() — byte swapping. In assembly you pre-compute the value or reach for bswap/ror.

  2. struct sockaddr_in — a 16-byte block of memory with a specific layout. No magic.

  3. Error handling helpers — perror, strerror. In assembly you're handed a raw negative integer and have to look it up yourself.

  4. getaddrinfo — the modern way to resolve hostnames. This one really IS painful in assembly: DNS means sending UDP packets to a name server, parsing the wire format, juggling multiple address families. The library genuinely saves you hundreds of lines here.

Building and Testing

Assemble and link:

bash
nasm -f elf64 server.asm -o server.o
ld server.o -o server
./server

In another terminal:

bash
nc localhost 8080
# Type anything and it will be echoed back

Or pipe a single line through nc:

bash
echo "Hello" | nc localhost 8080

Network Byte Order in Detail

x86 is little-endian: the least significant byte sits first in memory. Network protocols use big-endian, where the most significant byte comes first.

For port 8080 (0x1F90):

c
Little-endian (x86 memory): [0x90] [0x1F]
Big-endian (network order): [0x1F] [0x90]

In assembly, you can convert at runtime:

asm
mov ax, 8080 ; ax = 0x1F90
xchg al, ah ; Swap bytes: ax = 0x901F
; Or: ror ax, 8 ; Rotate right by 8 bits

For 32-bit IP addresses, start from the host-order value. 127.0.0.1 in host order is 0x7F000001, and bswap turns it into the value whose in-memory bytes are network order:

asm
mov eax, 0x7F000001 ; 127.0.0.1 in host order
bswap eax ; eax = 0x0100007F: stored as 7F 00 00 01
mov [rel sockaddr+4], eax ; sin_addr

If you write the constant already swapped (mov eax, 0x0100007F), it's ready to store as is. Swapping it again would put 01 00 00 7F in memory, which is 1.0.0.127.

Key Takeaways

  1. Sockets are file descriptors. After accept, you read and write exactly as you would a file. The kernel handles every TCP protocol detail.

  2. The socket API is thin. socket, bind, listen, accept are almost direct syscall wrappers. They add errno handling and not much else.

  3. Byte order is the main annoyance. htons and htonl handle the swap transparently in C. In assembly you have to remember to swap for every port and address yourself.

  4. The real complexity hides in the kernel. Our assembly server is short because the kernel takes care of TCP's three-way handshake, retransmission, flow control, congestion control. accept blocks until a connection is fully established — thousands of lines of kernel code run during that single syscall.

  5. This is how every network program works. Python's socket, Node.js net, Go's net, Java's ServerSocket — all of them end up calling these same syscalls. Higher-level languages pile on buffering, async I/O, and convenience layers, but the kernel interface stays the same.