The second part to the UDP Echo Server in C tutorial. In part II we add the server component of the code base and together with the client code from part I we’ll have a functioning application.
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.
On Windows our server setup code is nearly identical to the Mac/Linux version, with the main difference as discussed earlier being the bind() function call.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* server.c */
#if PLATFORM == PLATFORM_WINDOWS
intwindowsEchoServer()
{
SOCKET sock;
sockaddr_in serverAddr;
sockaddr_in clientAddr;
WSADATA wsaDat;
int wsaError = WSAStartup( MAKEWORD(2,2), &wsaDat );