How it works...

We will start by defining a string of size 255, and a server_Address variable of type sockaddr_in. This structure references the socket's elements. Then, we will invoke the socket function to create a socket by the name of serverSocket. A socket is an endpoint for communication. The address family that's supplied for the socket is AF_INET, and the socket type selected is the stream socket type, since the communication that we want is of a continuous stream of characters.

The address family that's specified for the socket is AF_INET, and is used for IPv4 internet protocols. The port number that's specified for the socket is 2000. Using the htons function, the short integer 2000 is converted into the network byte order before being applied as a port number. The fourth parameter, sin_zero, of the server_Address structure is set to NULL by invoking the memset function.

To enable the created serverSocket to receive connections, call the bind function to assign an address to it. Using the sin_addr member of the server_Address structure, a 32-bit IP address will be applied to the socket. Because we are working on the local machine, the localhost address 127.0.0.1 will be assigned to the socket. Now, the socket can receive the connections. We will invoke the listen function to enable the serverSocket to accept incoming connection requests. The maximum pending connections that the socket can have is 5.

You will be prompted to enter the text that is to be sent to the client. The text you enter will be assigned to the str string variable. By invoking the accept function, we will enable the serverSocket to accept a new connection.

The address of the connection socket will be returned through the structure of type sockaddr_in. The socket that is returned and that is ready to accept a connection is named toSend. We will invoke the send function to send the message that's entered by you. The socket at the client end will receive the message.

Let's use GCC to compile the serverprog.c program, as follows:

$ gcc serverprog.c -o serverprog

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

$ ./serverprog
Enter text to send to the client: thanks and good bye

Now, let's look at the other part of this recipe.