How it works...

So, we have defined a string of size 255 and a variable called client_Address of type sockaddr_in. We will invoke the socket function to create a socket by the name of clientSocket.

The address family that's supplied for the socket is AF_INET and is used for IPv4 internet protocols, and the socket type that's selected is stream socket type. The port number that's specified for the socket is 2000. By using the htons function, the short integer 2000 is converted into the network byte order before being applied as a port number.

We will set the fourth parameter, sin_zero, of the client_Address structure to NULL by invoking the memset function. We will initiate the connection to the clientSocket by invoking the connect function. By using the sin_addr member of the client_Address structure, a 32-bit IP address is applied to the socket. Because we are working on the local machine, the localhost address 127.0.0.1 is assigned to the socket. Finally, we will invoke the recv function to receive the message from the connected clientSocket. The message that's read from the socket will be assigned to the str string variable, which will then be displayed on the screen.

Now, press Alt + F2 to open a second Terminal window. Here, let's use GCC to compile the clientprog.c program, as follows:

$ gcc clientprog.c -o clientprog

If you get no errors or warnings, this means that the clientprog.c program has compiled into an executable file, clientprog.exe. Let's run this executable file:

$ ./clientprog
Data received from server: thanks and good bye

Voila! We've successfully communicated between the client and server using socket programming. Now, let's move on to the next recipe!