Welcome to the second part of the how to write a echo server in C. In this short second part we’ll finish up by adding the server code that our client in part I will use connect to over UDP/IP. Once again the code will work on all the major platforms Mac, Linux and Windows. Much of the socket address setup code and creation of a file descriptor is the same as the client application but the major difference with the server is that the server must bind its socket to port.
Move into the working directory created in Part I called UdpEcho
Create a file called server.c
Part II: The Server
If you read through Part I of this tutorial much of the code here will be instantly familiar. The server code uses the same platform object macros and selects a branch of code based on the system its being executed on.
C preprocessor setup, function prototypes and main
Here we notice the one key difference between the client code and the server code; the use of bind. In a nutshell; from wikipedia “When a socket is created using socket(), it is only given a protocol family, but not assigned an address.”. The assignment of an address is crucial for our sever because without it how else will clients know where to send packets. In other words a socket by itself can identify its protocol from the arguments passed to the socket() creation function but for a process which claims a socket to receive packets based on the networked computers port, there needs to be a one to one immutable relation between IP address and port number.
Mac and Linux Server Echo Loop
Our echo loop is extremely concise, read data from the bound socket, print a notification message and bounce it back to the same client address.