Building a socket server in C is a great introduction to the language as well as IPC mechanisms such as sockets and it can show you how simple it is to set up a server. For this installment, we’re going to do a single-threaded version.
So, let’s get started…
The Server
First I want to define some constants that we’ll use throughout. For some of these you may want to pass these in dynamically, but for this case I’m just hardcoding them here as constants:
1
2
3
4
5
6
#define SOCKET_ERROR -1
#define MAX_PENDING_CONNECTIONS 10
#define LOCALHOST "127.0.0.1"
#define PORT 8080
#define BUFSIZE 1024
We’ll put the server in a void function that we’ll call serve: void serve(), so
1
2
void serve() {
// Put all subsequent code here
Create the server socket file descriptor, usually created with with PF_INET, SOCK_STREAM, and with tcp IPPROTO_TCP.