简体   繁体   中英

Socket programming confusion with windows and unix/linux

Hello I am trying socket programming in c++. I need confirmation or say rejection for this logic. I think socket.h header files are designed for UNIX systems whereas for Windows everything is done with winsock.h .

Is this correct?

For windows, you need winsock2.h and ws2tcpip.h .

On Linux, you need sys/socket.h and sys/types.h for the socket functions and netinet/in.h for the IP related structs.

Some other differences:

  • Windows uses SOCKET for socket descriptors while Linux uses int
  • Windows has closesocket() to close sockets, while Linux uses close()
  • On Windows, you need to call WSAStartup() before calling any socket functions, and WSACleanup() when you are done using sockets.
  • On Linux, you can print errors from socket functions using perror() or strerror() . On Windows, you have to call WSAGetLastError() to get the error code and FormatMessage to get the error text.

Most platforms implement a BSD-compatible socket API, however different platforms do use different .h files to declare their API. So, to answer your question, Yes, Windows uses winsock.h (and winsock2.h ), whereas POSIX-based platforms like Unix/Linux use sys/socket.h instead ( socket.h is defined as part of the POSIX standard, but Windows is not a POSIX-compatible platform). If you want to write cross-platform code, you have to take this into account. As well as other differences, which @dbush outlined in his answer.

Every header file starting with "sys/..." is designed for UNIX environment. As for windows, they tend to use "win" as a prefix to every header file they use.

If you are interested in windows sockets (winsocks) i guess you should start from here .

As for UNIX sockets, this site seems very interesting and easy going :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM