8 ms·
Ask HN: Resources for Building a Webserver in C?
I'm starting to work with C and would like to build a webserver. I've found a few interesting writeups but would love to hear from the community.
What's your favorite book/post/lecture/whatever? I'd also be interested in opinionated writeups/positions.
- jart 4y agoHere's a 2000 line web server I wrote in C (with a focus on readability) which runs https://ipv4.games/ https://ipv4.games/ You can read the code at https://github.com/jart/cosmopolitan/blob/master/net/turfwar/turfwar.c https://github.com/jart/cosmopolitan/blob/master/net/turfwar... This web server runs on a single VM. It was handling about 300 write requests per second earlier today. You can monitor its metrics here: https://ipv4.games/statusz https://ipv4.games/statusz It uses *NSYNC as its multi-threaded locking primitives, which was designed by the guy who created Google's lock server. This service is frequently targeted by hackers so you can learn a lot about things like DDOS protection by reading the source.
- mmmmwhat 4y agoyou could try using https://libuv.org/ https://libuv.org/ and https://github.com/h2o/picohttpparser https://github.com/h2o/picohttpparser
- cinntaile 4y agoSomeone on HN made this [0] a couple of weeks or months ago. You code a web server to solve each of the different problems. It's language agnostic but it looks like a great way to learn. [0] https://protohackers.com/ https://protohackers.com/
- deleted 4y ago[deleted]
- jjice 4y agoIf you want to do something simple, read Beej's Guide to Networking (many other have recommended it in this thread) to learn networking fundamentals and C APIs. Next, learn about HTTP - MDN is a good resource, but may go too in depth for this project at times. HTTP 1.1 is super simple. The best thing about HTTP? It's all just plain text and newlines. Parsing it is super easy. This is a good learning exercise - good luck on it.
- nam17887 4y agoI've written a fully functioning web server using a managed language, with SSL, multi-threading, Keep-Alive and chunked content encoding. I suggest to start with understanding the HTTP protocol by reading the RFC. The most important part is how to start and end the HTTP message (by closing connection, by Content-Length, or by chunked encoding). Then next important bit is how to receive the HTTP message. Network APIs will ask for number of bytes to receive, so you'll need to know exactly how the message ends. Stick with the RFC, programming language doesn't matter because socket APIs are very much the same.
- rqmedes 4y agoIf you are looking at performance I found pulling this code apart a great learning experience. https://github.com/fredrikwidlund/libreactor https://github.com/fredrikwidlund/libreactor
- 082349872349872 4y agoIf you wish, use the source. (Almost?) all early webservers were written in C.
- shanebellone 4y agoBeing largely unfamiliar with C, I would prefer conceptual resources over source code. The why is more important than the how. Hopefully that makes sense?
- ihatepython 4y agoOne of my favorite things to read is RFC 1945
- mcculley 4y agoUnfortunately, having done the same, there are a lot of lessons learned in existing source code that you won’t find elsewhere.
- convolvatron 4y agoconceptually things are pretty limited - this is really simple if you are just playing around, and are just doing http 1 o bind a socket o manage incoming connections o parse http headers o 'routing' - demultiplex handlers based on URL o encode response unless its a little embedded thing one usually uses some kind of select/epoll machinery to multiplex the work on each channel. I guess thread-per-request is another model that works at moderate connection counts. it helps to have some decent way of representing the header to send to the handler, C doesn't really have a great story here I think the only funky thing is dealing with all the various body modes. so you will need to make some kind of protocol to deal with handlers and incremental updates if that's a thing for your use case. I would just do the normal thing, read the rfc and spit out a couple hundred lines that talks to your browser...and then decide where if anywhere you need to go from there
- shanebellone 4y agoA little context: I'm specifically interested in compressing my analytics stack. I'm currently interacting with HTTP Messages at a higher level. The problem, as I see it, is the webserver is already doing this work but without useful output. I'd like to implement my analytics paradigm natively at the webserver level.
- LargoLasskhyfv 4y agohttps://learnbchs.org/ https://learnbchs.org/ ?
- Mikhail_Edoshin 4y agoThis one is more about writing web server applications in C. The stack already has both a webserver that talks with the app via FastCGI, and a database (SQLite).
- rzzzt 4y agoBeej's guide to network programming: https://beej.us/guide/bgnet/ https://beej.us/guide/bgnet/
- shanebellone 4y agoBookmarked. Thanks for the link.
- hsn915 4y agoThis guide is great for introducing the bsd socket api but this is really not the API you want to use if you want to create a production quality web server in C in 2022. You need the uring io API.
- e12e 4y agoMight want to check out: https://unixism.net/loti/tutorial/webserver_liburing.html https://unixism.net/loti/tutorial/webserver_liburing.html (and maybe the older tutorial too): https://unixism.net/2019/04/linux-applications-performance-introduction/ https://unixism.net/2019/04/linux-applications-performance-i...
- tareqak 4y agohttps://kernel.dk/io_uring.pdf https://kernel.dk/io_uring.pdf ?
- qntty 4y agoUnix Network Programming by W. Richard Stevens and parts of The Linux Programming Interface by Michael Kerrisk
- shanebellone 4y agoOrdered. Thanks!
- gpderetta 4y agoThis is pretty much the bible on the topic. At least on sockets programming in general, I don't think it covers HTTP.
- barbarbar 4y agoMaybe redbean made by jart?
- AlexeyBrin 4y agoHands-On Network Programming with C by Lewis Van Winkle is a really good intro book for network programming with C.
- shanebellone 4y agoOrdered. Thank you for the recommendation.
- Kukumber 4y agoFor embedded: https://github.com/cesanta/mongoose/ https://github.com/cesanta/mongoose/
- synergy20 4y agothis is commercial now? its open source forked version is civetweb
- Kukumber 4y agoall my work is open source, so i don't mind the licence, it's dual licensed if i remember correctly, GPL or commercial thanks for letting me know about civetweb, looks like it is based on a very old version?
- User23 4y agoUnix Network Programming by Stevens and TCP/IP Illustrated by Fall and Stevens are must reads. There are many subtleties and pitfalls in writing low level network code and those books comprehensively cover everything. Edit: I’ve heard that the first edition of TCP/IP illustrated has considerably more readable prose, so if you’re not doing IPv6 maybe get it instead. Apparently the 2nd edition with Fall is more of a rewrite with a considerable number if technical errors so I can’t recommend it having not read it.
- st_goliath 4y ago"Write a tiny web server in C" was a standard exercise when I was in high school, and later again in university. I think I did that at least 3 times as an assignment so far. I reused the final version for a different university exercise instead of bothering with Tomcat as I was required, and back in 2015, dumped the end result here: https://github.com/AgentD/websrv https://github.com/AgentD/websrv where I kept adding to it for a while for fun. The HTTP 1.x protocol itself is pretty dead simple (if you ignore chunked requests/responses and such) and the more interesting part was actually the socket code. Back in school, our teacher had us write a simple forking server and consult the corresponding man pages (man 2 socket, man 7 socket, man 7 tcp). It was an acceptable minimal solution to not even look at the client request, respond with a static string containing a dummy response header and HTML page, which absolutely works. Bonus points for parsing the request path and sending a file back, more extra points if the path was a directory and your server sends back an "index.html" file, further points if it instead generates an HTML directory listing on the fly. When I visited our former teacher a couple years ago, he had modified the exercise somewhat. He brought a Beagle Bone Black with him to class, with a bunch of I2C sensors attached to it, and the extended exercises now revolve around reporting temperature/humidity/... to the browser. So, for "resource" I recommend the HTTP example on Wikipedia, as well as "Beej's guide to network programming" (as have others), as well as the man pages for quick reference.
- 0xfaded 4y agoI agree that writing the network code is more interesting. Perhaps make a really simple proxy server that accepts connections and forwards data to another http server
- mobilio 4y agoBeej is fantastic resource!
- shanebellone 4y agoThis sounds like a ton of fun. I would have enjoyed this educational path.
- st_goliath 4y ago
- mobilio 4y agoThis is priceless https://acme.com/software/thttpd/ https://acme.com/software/thttpd/
- coolandsmartrr 4y agoI remember using this tutorial to build a web server that handles sockets. Short source code, excludes edge cases, but useful to understand the gist of web servers. https://www.ibm.com/support/pages/how-does-webserver-actually-work-find-out-nweb https://www.ibm.com/support/pages/how-does-webserver-actuall...
- shanebellone 4y agoThe tutorial has been moved to https://nmon.sourceforge.net/pmwiki.php?n=Site.Nweb https://nmon.sourceforge.net/pmwiki.php?n=Site.Nweb. Thanks for the share.
- _8j50 4y agoRead the mongoose source code.
- locriacyber 4y agoComplete OpenBSD + Sqlite + C + httpd toolkit for building websites. http://bsd.lv/ http://bsd.lv/ I recommend swapping out C for a safer&more productive language.
- tmtvl 4y agoIs there a safe and productive language that produces binaries that run fast? Between the rising energy prices and CO2 pollution it would be very irresponsible to use languages like Python or Ruby.
- jen20 4y agoYes, Rust.
- tmtvl 4y agoYou're right. I actually managed to skip over "small" in front of "binaries", so that's my mistake, but for fat binaries with decent performance Rust is a great language, as long as you don't care about glacial development speed.
- hamdouni 4y agoGo help you save more CO2 by compiling your code in a blink
- tmtvl 4y agoYeah, fast compilation (like C has) helps.
- rnmmrnm 4y agohttps://tools.suckless.org/quark/ https://tools.suckless.org/quark/ is a honorable mention, very elegant code.
- samsquire 4y agoYou might find my epollserver interesting. It multiplexes multiple clients (sockets) over a thread, so you can write an event loop in each thread and serve far more requests per thread than you could if it was one thread per client or one process per client. (epollserver_threaded.c) It uses a thread safe multiconsumer multiproducer ringbuffer to communicate between threads. https://github.com/samsquire/epoll-server https://github.com/samsquire/epoll-server I use Alexander Krizhanovsky's of Tempesta technologies Lock-Free Multi-Producer Multi-Consumer Queue on Ring Buffer https://www.linuxjournal.com/content/lock-free-multi-producer-multi-consumer-queue-ring-buffer https://www.linuxjournal.com/content/lock-free-multi-produce...
- shanebellone 4y agoThis sounds really interesting. Thanks for the share.
- samsquire 4y agoThanks for your kind thanks. I'm currently working on a generalised approach to structuring multiple multithreaded components that run kernel threads and lightweight threads similar to golang. My 1:M:N userspace scheduler multiplexes N lightweight threads onto M kernel threads but it's a different repository. It has one kernel thread and preempts loops by setting them to their limit. Ideally they should be merged into one codebase. https://GitHub.com/samsquire/preemptible-thread https://GitHub.com/samsquire/preemptible-thread
- vetelko 4y agoAlthttpd source is great resource https://sqlite.org/althttpd/file/althttpd.c https://sqlite.org/althttpd/file/althttpd.c
- bjourne 4y ago> I'd also be interested in opinionated writeups/positions. Ok then! Writing a web server in C is bloody stupid. A web server's performance is mostly limited by concurrency issues and various IO latencies, not by how fast the machine code runs. Thus, there are zero advantages to writing a web server in C and mountains of disadvantages. Save your time and write your web server in a good language, Java, Go, Python, Nim, but not C.
- shanebellone 4y agoI've built one with Python along with a custom WSGI app. Also, Apache and NGINX say hello.
- rwmj 4y agoHere's a fun webserver I wrote 20 years ago. It uses a pool allocator to make allocations easy to track (gives you a lot of the benefits of garbage collection, but from pure C), and it also uses an interesting "inversion of control" (similar to "green threads" or coroutines) allowing the server to be written as straight-line code but actually being implemented using poll. It actually ran a production site at an old company I worked at until fairly recently. http://git.annexia.org/?p=c2lib.git;a=tree http://git.annexia.org/?p=c2lib.git;a=tree http://git.annexia.org/?p=pthrlib.git;a=tree http://git.annexia.org/?p=pthrlib.git;a=tree http://git.annexia.org/?p=rws.git;a=tree http://git.annexia.org/?p=rws.git;a=tree