Categories
C/C++

Socket programming in Linux with GCC

Linux is the paradise of programmers. It facilitates programmers with the numerous tools and flexibility. Programmers easily can develop and test their code in Linux freely. Linux has many compilers and programming languages which majority of them are freely available with good documentation, by contrast of Windows. This post demonstrates of how to write simple chat application with C programming language.

Fortunately, Linux contains necessary header files and needed libraries for communication and make connection. The following header files in Linux socket programming are needed for both client and server applications.

The chat application should be written as two separate applications. The first is client application and the other is server application and each can run in separate computer.

Bear in mind that you need to compile and run the application in Linux terminal or console. If you need more information about how to compile C application with GCC compiler in Linux click here.

The following section reflects the server side application,

In server side, at first server application tries to make a TCP connection. If the application faces problem during creating TCP connection it will shows message and exit. Then in the next step if will ask user to set IP address and port. When user entered set the parameters it will check the availability of the port and IP address. If either is in use then server applications prompts Busy message. Otherwise, it will show success message and listen to the port for client to connect to server.

After client application connected to the server successfully, both applications can start communication easily. Finally, the connection will be closed if the server user types “exit” in message part.

The code of client application is like below,

The client application is different from server application. In the client no TCP connection is created and just IP address and port which server listens to them need to be set in the client. If any problem will be happened, the application terminates. Otherwise, the client connects to server and the communication will be started. Like server program, if client user types exit in message part, the connection will be terminated.

Exit mobile version