Porting the socket program from Linux to Windows

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.