C++ Cross platform Network programming

Started by
12 comments, last by Saruman 15 years, 4 months ago
Quote:Original post by samoth
Quote:Original post by Evil Steve
Plain BSD sockets. On Windows you'll still need to call WSAStartup and WSACleanup, but that's just two function calls.
[...]
So I can use the same code, just change the headers & add in the funstion calls?
[...]
Yup, exactly.
Almost. You need to make a typedef for the socket and a typedef for a "raw pointer", since they're different on Windows and Linux. Otherwise your compiler will choke on some functions.
You'll need to define the raw pointer type as char* for Windows and void* for Linux, and the socket type as SOCKET for Windows and int for Linux.
Ah, I forgot about those. Does SOCKET exist at all on Linux?
Advertisement
On Windows, SOCKET is just an int typedef. AFAIK.
Quote:Ah, I forgot about those. Does SOCKET exist at all on Linux?

No it is just a file descriptor.
Quote:On Windows, SOCKET is just an int typedef. AFAIK.

No it is a UINT_PTR which depending on the platform (64 or 32) has different sizes.
I seem to just be saying the same things on different places on the net :(
In my experience of working across next-gen (current-gen?) console platforms, you can't rely on your socket api being the same across platforms. To a certain extent this is also true of PC platforms. More so in particular when you consider matchmaking functionality, which may be completely different across different platforms. If you want my advice, work with the native socket API of your chosen platform (which on PC platforms does tend to be a derivative of Berkeley sockets), and don't be afraid to separate your code so it will compile cleanly on each target platform, and just give it a common interface so some code can be shared, that's just cross-platform coding sense.

Also, I just wanted to add that the htons and htonl functions are C-style functions which convert the byte ordering of packet data to little endian. Obviously, on PPC platforms such as the old-style Mac (Pre Core2) which are already little endian, nothing needs to be done. On big endian platforms such as Intel x86 (windows, some linux variants), the bytes need to be reordered in reverse so that data transmitted over the network can be properly processed on different platforms.
Quote:Original post by TheGilb
Obviously, on PPC platforms such as the old-style Mac (Pre Core2) which are already little endian, nothing needs to be done. On big endian platforms such as Intel x86 (windows, some linux variants), the bytes need to be reordered in reverse so that data transmitted over the network can be properly processed on different platforms.


Just to clear up PPC is big endian and x86 is little endian.

This topic is closed to new replies.

Advertisement