Today suddenly want to try the pure socket programming on the two systems code coincident amount of how much, as long as not using VC custom macros (such as sockets, SOCKADDR, etc.) feel the code overlap is very large.
For example, the simplest TCP client and server-side dialog, in the VC with int instead of the socket macro, the struct sockaddr_in replace the SOCKADDR_IN macro.
Then the difference is just the header file and Windows extra load/Shut down the socket font code.
Unix/linux
#include <sys/socket.h> #include <netinet/in.h>//Sockaddr_in#include <arpa/inet.h> //inet_ Ptonint Main (int argc, char* argv[]) { //TODO: Generic Code}
Windows
#include <WinSock2.h> #include <WS2tcpip.h> #pragma comment (lib, "Ws2_32.lib")// Close file descriptor is not supported directly on Windows # # # Close closesocket//Windows needs extra load and shut down the socket library # define LOAD_WIN_SOCK_LIB wsadata Wsadata; if (WSAStartup (Makeword (2, 1), &wsadata)! = 0) err_quit ("Load Windows Socket font failed!"); if (Lobyte (wsadata.wversion)! = 2 | | Hibyte (wsadata.wversion)! = 1) {wsacleanup (); Err_quit ("Initialization of version number failed");} #define CLOSE_WIN_SOCK_LIB wsacleanup (); int main () {load_win_sock_lib//TODO: Generic Code Close_win_sock_lib}
The above two code ignores the other header files, the definition of global variables and the last return 0;
Err_quit is I directly with the Apue error handling function, change to Fprintf+exit also can.
If you need only one file, you can use a cross-platform macro to define
#ifdef specific code for the win32//todo:windows platform specific code #else//todo:linux platform #endif
Then the egg, after all, is written on Windows only to hand in the homework, and Windows also provides CAsyncSocket and CSocket, etc., there is no need to persist in cross-platform.
Porting the socket program from Linux to Windows