Communication Networks/Berkeley Socket API< Communication Networks
It will be mentioned here, but also probably in every sub-chapter of this section that the intention of these chapters, much less of the entire book, that the purpose of this is not to teach network programming. What these chapters do aim to do is provide a fast and dirty listing of available functions, and demonstrate how they coincide with our previous discussions on networking. For further information on the subject, the reader is encouraged to check out networking concepts on the programming bookshelf.
This page is not designed to be an in-depth discussion of C socket programming. Instead, this page would like to be a quick-and-dirty overview of C, in the interests of reinforcing some of the networking concepts discussed earlier.
C and UnixEdit
This section will (briefly) discuss how to program socket applications using the C programming language in a UNIX environment. The next section will then discuss the differences between socket programming under Windows, and will explain how to port socket code from UNIX to Windows platforms.
C and Windows (Winsock)Edit
Programming sockets in Windows is nearly identical to programming sockets in UNIX, except that windows requires a few different additions:
- Use <Winsock.h>
- Link to ws2_32.dll
- Initialize Winsock with WSAStartup( )
The first 2 points are self-explanatory, and are actually dependant on your compiler, which we will not go into here. However, the 3rd point needs a little explaining. We need to initialize winsock before we can use any of the socket functions (or else they will all return errors). To initialize, we must create a new data object, and pass it to the initialization routine:
And we must pass a pointer to this structure, along with the requested version number for winsock to the function:
WSAStartup(MAKEWORD(2, 0), &wd);
The MAKEWORD macro takes two numbers, a major version number (the 2, above), and a minor version number (the 0, above). For instance, to use Winsock2.0, we use MAKEWORD(2, 0). To use Winsock1.1, we use MAKEWORD(1, 1).
Also, it is important to note that Windows does not allow sockets to be read and written using the generic unix read( ) and write( ) functions. In windows, you should instead use the recv( ) and send( ) functions. Also, people who are familiar with windows should know that windows treats sockets as an I/O handle, so they can also be accessed with the Windows generic read/write functions ReadFile( ) and WriteFile( ).
Winsock, and windows in general also have a number of other functions available in winsock.dll, but also in other dlls (like wininet.dll) that will facilitate higher-level internet operations.