This guide will explain how to create a TCP/IP Server on Raspberry Pi 3 B, running Raspbian (or Raspbian Lite). The source code file is written in C/C++ language.
The source code is very simple and short. The code below is available on this website, and uses Linux sockets to create a TCP/IP server on port 8888.
The program at first creates a socket descriptor. Then, it initializes a sockaddr_in structure (it contains the address of the server itself, the connection port number and the type of communication), and binds it to the socket. After that, the server is set in listening mode. And when an incoming connection arrives from a client (a Telnet connection from Putty on the PC), it opens the connection and suddenly closes and exit the program.
int socket_desc , new_socket , c;
struct sockaddr_in server , client;
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
printf("Could not create socket");
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
listen(socket_desc , 3);
//Accept and incoming connection
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
new_socket = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
First of all, you need to create a file with "c" extension and copy it on your Raspberry Pi, for example using Samba from your PC (a guide is available here). I often use this method, because editing a text file on the PC, for example using Notepad++, is faster than doing it on the Raspberry using nano editor. You can edit the file many times on the PC, and when the file is ready copy-paste it on the Pi by using Samba.
In this example, I created a file called "server.c", and included it in the folder "server" located inside the home. In order to compile and run the program using gcc, type the following commands:
gcc server.c -o server
The server program is now waiting for a connection coming from a TCP/IP client. You can connect from your PC using Putty. You just need to write the IP address of your Raspberry (example: 192.168.0.13) and the TCP port (8888). Connection protocol is "Telnet" (no encryption). In case you don't know the IP address of your Pi, you can use Advanced IP Scanner or similar programs.
This guide simply explained how to compile a C/C++ program using gcc compiler on Raspbian OS. In the next lesson, I will show how to continuously communicate using TCP/IP, by sending and receiving data.