Simple TCP Server Socket in C

In this post I will explain how to code a very simple and minimalist C TCP server using sockets in C. In many projects, I had to use the sockets to communicate with another remote (or sometime local) component. Each time, I must Googling the terms “Simple TCP server Socket in C” because I know that the minimalist code is simple but I never save this simpler code in my file. So with this post, I have a simple version of server socket 🙂 . Before beginning I just want to prevent the readers that this arcticle will not explain in detail the different C structures that will be used but just explain the important pieces of code to have a minimalist server socket.

The sockets

The sockets are officially born in the Berkeley University at the beginning of 1980 for the BSD (Unix system). After that, this programming interface is available for (almost) each language (C, C++, C#, Java, Python, …). The sockets permit to applications to send and receive data. A socket uses a communication technologie to work but actually the most used communication stack is the TCP/IP stack. You must know that a TCP/IP socket can be several types (Datagram, Stream or RAW). In this post we will explain the Stream (TCP) because it is the most used and the RAW socket deserves a dedicated post. For the UDP (datagram) server socket, a future article will be created very soon

The stream server behavior

Before start to develop the server, it’s very important to understand its classic behavior. The next scheme illustrates very well this behavior.

  Socket() : Creation of the server socketBind() : Attach the socket to a specific local port

Listen() : Make the socket in listening mode

Accept() : Blocking method. Wait for an incoming connection request from a client

Read() : Read data from the new accepted client

Write() : Optionally send back data to the client

Close() : Once Finished, close the connection with this client

This behavior is very minimalist and an important thing to memorize is that this server process client per client and not in parallel. A real and performant server must be able to handle several clients in parallel but this concept if out of the scope for this post.

The code of stream server socket

Let’s go to the code. Here is all the code of the server. All comments are directly in the code. I think that if you need to develop a server socket in C, these comments are sufficient to understand the code.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <errno.h>

#define MY_PORT		9999
#define MAX_BUF		1024

int main()
    int sockfd;
	struct sockaddr_in self;
	char buffer[MAX_BUF];

	/** Create streaming socket */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)

	/** Initialize address/port structure */
	bzero(&self, sizeof(self));
	self.sin_family = AF_INET;
	self.sin_port = htons(MY_PORT);
	self.sin_addr.s_addr = INADDR_ANY;

	/** Assign a port number to the socket */
    if (bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0)

	/** Make it a "listening socket". Limit to 20 connections */
	if (listen(sockfd, 20) != 0)

	/** Server run continuously */
	while (1)
	{	int clientfd;
		struct sockaddr_in client_addr;
		int addrlen=sizeof(client_addr);

		/** accept an incomming connection  */
		clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
		printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

		/** Echo back the received data to the client */
		send(clientfd, buffer, recv(clientfd, buffer, MAX_BUF, 0), 0);

		/** Close data connection */

	/** Clean up */
	return 0;

 The compilation

To compile this code, I use the classical GCC compiler under linux with the following command:

gcc -W -Wall -Wextra tcp_server.c -o tcp_server

It’s possible that you have a warning but the server work correctly.

Test your TCP server locally

To test is locally, just run it and start a new TCP connection on it with netcat on linux for example

cyrill@cyrill-ubuntu:~/Desktop/test$ ./tcp_server

and in another console:

cyrill@cyrill-ubuntu:~/Desktop/test$ nc 9999

Note that the server listen for incomming connection on tcp port 9999. This value is hardcoded. In the server console, the message “ connected” must be displayed (with another port) and in the client (netcat) console, if you write and send “Hello”, the server send you back the same message.

Upgrade your server

In this last paragraph, some ideas to upgrade your server 🙂

  • Allow user to choose the server port when he starts it : example : ./tcp_server [port]
  • Allow user to choose the size of server buffer : example : ./tcp_server [port] [buf_size]
  • Allow many client to be connected simultanously (look around select function or epoll (if you want a challenge 🙂  ))
Bookmark the permalink.


  1. Hello ! Thanks for this article. It is simple and permits to understand easily the base of TCP socket. Best Regards ! John

  2. Hello admin, i must say you have hi quality articles here.
    Your blog should go viral. You need initial traffic only.
    How to get it? Search for; Mertiso’s tips go viral

  3. I see you don’t monetize your site, don’t waste your traffic, you can earn extra
    cash every month because you’ve got high quality content.
    If you want to know how to make extra money, search for: best adsense alternative Wrastain’s tools

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.