I know, Windows doesn't use UNIX sockets while Mac OS does. Until this point my software was cross-platform without any code changes. But now I want it to do some network communication. I know about POSIX sockets, but I know nothing about Windows' ones. The goal is to implement a simple cross-platform socket server.
Could you please explain to me the differences between POSIX and Winsock sockets and how I may go about writing cross platform networking code?
There are many libraries and toolkits that support cross platform sockets, depending on what you are doing, you can use (to name a few):
If you don't want to have a dependency on an external library, all of the above packages have fairly permissive licenses, so you can use their code as a reference.
WinSock versus POSIX Sockets
WinSock and POSIX sockets work in a similar manner - mainly because Windows sockets were originally based on code from BSD:
However, there are a few things you'll need to handle differently if you want to write "socket-library-agnostic" code.
Note: The following examples have been tested using Code::Blocks and GCC on Windows XP (x86) and Debian Testing (AMD64).
The header and lib files are different
You'll need to include different header files depending on whether you're using Windows or not:
You'll also need to link with
Ws2_32
lib file on Windows.WinSock requires initialisation and cleanup.
The functions below illustrate how you can initialise WinSock v1.1 and clean up afterwards:
Socket handles are UNSIGNED on Winsock
For POSIX-style sockets, you can simply use
int
to store a socket handle. Invalid sockets are indicated by a negative value.However, WinSock sockets are UNSIGNED integers, with a special constant (
INVALID_SOCKET
) used instead of negative numbers.You can abstract the differences by
typedef
ing SOCKET asint
on POSIX and hiding the "valid socket" check behind a macro or function.Sockets are closed differently
The function below illustrates the differences:
In general though, they're pretty similar.
If you stick to "common" functions (such as
send()
orrecv()
) and avoid platform-specific stuff (such asWSAWaitForMultipleEvents()
) then you should be fine.The regular sockets (those in AF_INET address family) which you need to build a socket server are equally supported on all platforms.
Do not confuse them with Unix sockets (those in AF_UNIX address family) - such sockets are highly specific for a Unix world, and are used for a highly specific goals. You wouldn't ever need them for a simple socket server application.
I can also suggest the plibsys library: works on both Windows and UNIX systems (see the full list on the project page) with various compilers. Supports IPv4 and IPv6. It has the tests where you can see the usage examples. The library itself is lightweight and portable.