93 while (1) {
94 /* wait for a call */
95 ClntDescriptor = accept(SrvrDescriptor,0,0);
106 /* read client command */
107 memset(InBuf,0,sizeof(InBuf));
108 read(ClntDescriptor,InBuf,sizeof(InBuf));
113 /* process the command */
114 Respond();
115 }
116 }
117
Note the #include files. Also, here are some other notes on programming:
• On Solaris machines, you may need to add -lsocket and possibly -lxnet to your compile command.
• On some platforms, you will have to be more careful with C casts than I have in the code above, for
example in the second argument to connect(). This is especially true for C++.
• Though in the code here we have not done error-checking, in order to avoid distraction from the main
concepts, you definitely should check the return values of the system calls, so that if one fails you will
know which one it was.
• Even after a socket is closed, TCP will keep that socket alive for a while (e.g. 30 seconds or so), just
in case there are still some packets to come in. Thus a given port will not be immediately reusable,
unless we call setsockopt() with SO REUSEADDR after opening the socket on the server end.20
Let's see how the programs work, taking the client first.
Line 23:
20This should be used with care, though, since the streams from two clients might get mixed.
16
We have chosen to put our server on port 2000. Ports 0-1023 are reserved for the so-called well-known
ports corresponding to standard TCP/IP services. You can see a list of well-known ports in the UNIX file
/etc/services.
Line 24: We will use arrays for our read() and write() system calls. They need to be large enough for the
data we send. In this case, 1000 characters will be sufficient. Note carefully, though, that this limit is NOT
there for the purpose of keeping our packets small; we can send as long a message as we like, with a single
call to write(). Remember, TCP will break up long messages into shorter ones for us, without us even seeing
it, so we do not have to worry about it.
Lines 36-39:
We open a socket, using the socket() system call. The first parameter indicates whether this is an Internet
socket, versus a socket purely local to this machine (a "UNIX socket"), not going out onto the Internet; the
Internet case here is designated by AF INET. The second parameter indicates the service, i.e. TCP, UDP or
others; it is TCP in this case, designated by SOCK STREAM.21 We have defaulted the third parameter here
(and will not worry about what other possibilities there are for it).
Overview of Computer Networks
Start from the beginning
