Skip to content

Instantly share code, notes, and snippets.

@XielQs
Last active July 6, 2025 20:55
Show Gist options
  • Save XielQs/61a0c489b42da8de896ad979ee2e7a74 to your computer and use it in GitHub Desktop.
Save XielQs/61a0c489b42da8de896ad979ee2e7a74 to your computer and use it in GitHub Desktop.
Simple web server written in assembly x86_64
section .bss
buff resb 1024
section .data
http200:
db "HTTP/1.1 200 OK", 0dh, 0ah ; \r\n
db "Server: XielQ", 0dh, 0ah
db "Content-Type: text/html", 0dh, 0ah
db 0dh, 0ah
db 'XielQ on Top!!', 0ah
http200Len equ $ - http200
err db 'An error occured while creating the webserver', 0ah
errLen equ $ - err ; length of err
optval dd 1 ; optval
sockaddr_struct:
dw 2 ; sin_family
dw 0xB90B ; sin_port (little-endian hex of 3001)
dd 0 ; sin_addr.s_addr = 0.0.0.0
dq 0 ; 0-padded
section .text
global _start
; rdi rsi rdx r10 r8 r9
_start:
mov rax, 41 ; syscall socket
mov rdi, 2 ; AF_INET
mov rsi, 1 ; SOCK_STREAM
mov rdx, 0 ; protocol
syscall
mov rbx, rax ; store socket fd to rbx
cmp rax, 0 ; compare if rax - 0
jl error ; jump if rax is less than 0 (so basically if there is a error)
mov rax, 54 ; syscall setsockopt
mov rdi, rbx ; socket fd
mov rsi, 1 ; SOL_SOCKET
mov rdx, 2 ; SO_REUSEADDR
mov r10, 1 ; optval
mov r8, 4 ; sizeof(int)
syscall
mov rax, 49 ; syscall bind
mov rdi, rbx ; socket fd
lea rsi, sockaddr_struct ; sockaddr_in
mov rdx, 16 ; sizeof(sockaddr_in)
syscall
cmp rax, 0 ; compare if rax - 0
jl error ; jump if rax is less than 0 (so basically if there is a error)
mov rax, 50 ; syscall listen
mov rdi, rbx ; socket fd
mov rsi, 20 ; 20 conn max
syscall
cmp rax, 0 ; compare if rax - 0
jl error ; jump if rax is less than 0 (so basically if there is a error)
accept:
mov rax, 43 ; syscall accept
mov rdi, rbx ; socket fd
mov rsi, 0 ; addr
mov rdx, 0 ; addr length
syscall
mov r12, rax ; store client socket fd to r12
cmp rax, 0 ; compare if rax - 0
jl error ; jump if rax is less than 0 (so basically if there is a error)
mov rax, 0 ; syscall read
mov rdi, r12 ; client fd
mov rsi, buff ; buffer
mov rdx, 1024 ; max byte
syscall
cmp rax, 0
je close_client
mov rax, 1 ; syscall write
mov rdi, r12 ; client socket fd
mov rsi, http200
mov rdx, http200Len
syscall
jmp close_client
close_client:
mov rax, 3 ; syscall close
mov rdi, r12
syscall
cmp rax, 0 ; compare if rax - 0
jl error ; jump if rax is less than 0 (so basically if there is a error)
jmp accept
error:
mov rax, 1 ; syscall write
mov rdi, 2 ; fd for stderr
mov rsi, err ; err msg
mov rdx, errLen ; msg len
syscall
mov rax, 60 ; syscall exit
mov rdi, 1 ; exit with 1
syscall
; nasm -f elf64 -o server.o simple_web_server.asm && ld server.o -o server
; it will open a port at :3001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment