We start by defining two strings by the names of msgReceived and msgforclient, both of which are of size 255. These two strings will be used to receive the message from and send a message to the client, respectively. Then, we will define two variables, server_Address and client_Address, of type sockaddr_in. These structures will referenc the socket's elements and store the server's and client's addresses, respectively. We will invoke the bzero function to initialize the server_Address structure, that is, zeros will be filled in for all of the members of the server_Address structure.
The server, as expected, waits for the datagram from the client. So, the following text message is displayed on the screen: Waiting for the message from the client. We invoke the socket function to create a socket by the name of UDPSocket. The address family that's supplied for the socket is AF_INET, and the socket type that's selected is datagram. The members of the server_Address structure are initialized to configure the socket.
Using the sin_family member, the address family that's specified for the socket is AF_INET, which 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. Then, we use a special IP address, INADDR_ANY, to assign an IP address to the socket. Using the htonl function, the INADDR_ANY will be converted into the network byte order before being applied as the address to the socket.
To enable the created socket, UDPSocket, to receive connections, we will call the bind function to assign the address to it. We will call the recvfrom function to receive the message from the UDP socket, that is, from the client machine. The message that's read from the client machine is assigned to the msgReceived string, which is supplied in the recvfrom function. A null character, \0, is added to the msgReceived string and is displayed on the screen. Thereafter, you will be prompted to enter the reply to be sent to the client. The reply that's entered is assigned to msgforclient. By invoking the sendto function, the reply is sent to the client. After sending the message, the following message is displayed to the screen: Reply to the client sent.
Now, let's look at the other part of this recipe.