[英]Socket programming confusion with windows and unix/linux
Hello I am trying socket programming in c++. 您好,我正在尝试使用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
. 我认为
socket.h
头文件是为UNIX系统设计的,而对于Windows,一切winsock.h
完成。
Is this correct? 这个对吗?
For windows, you need winsock2.h
and ws2tcpip.h
. 对于Windows,你需要
winsock2.h
和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. 在Linux上,套接字功能需要
sys/socket.h
和sys/types.h
,IP相关结构需要netinet/in.h
Some other differences: 其他差异:
SOCKET
for socket descriptors while Linux uses int
SOCKET
作为套接字描述符,而Linux使用int
closesocket()
to close sockets, while Linux uses close()
closesocket()
关闭套接字,而Linux使用close()
WSAStartup()
before calling any socket functions, and WSACleanup()
when you are done using sockets. WSAStartup()
,并在完成套接字使用后调用WSACleanup()
。 perror()
or strerror()
. perror()
或strerror()
从套接字函数中打印错误。 On Windows, you have to call WSAGetLastError()
to get the error code and FormatMessage
to get the error text. WSAGetLastError()
来获取错误代码,并调用FormatMessage
来获取错误文本。 Most platforms implement a BSD-compatible socket API, however different platforms do use different .h
files to declare their API. 大多数平台都实现与BSD兼容的套接字API,但是不同的平台确实使用不同的
.h
文件来声明其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). 因此,要回答你的问题,是的,Windows使用
winsock.h
(和winsock2.h
),而像在Unix / Linux基于POSIX的平台上使用sys/socket.h
代替( socket.h
被定义为POSIX标准的一部分,但Windows不是POSIX兼容平台)。 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.
以及其他差异,@ dbush在其答案中概述了这些差异。
Every header file starting with "sys/..." is designed for UNIX environment. 每个以“ sys / ...”开头的头文件都是为UNIX环境设计的。 As for windows, they tend to use "win" as a prefix to every header file they use.
对于Windows,他们倾向于使用“ win”作为所使用的每个头文件的前缀。
If you are interested in windows sockets (winsocks) i guess you should start from here . 如果您对Windows套接字(winsocks)感兴趣,我想您应该从这里开始。
As for UNIX sockets, this site seems very interesting and easy going :) 至于UNIX套接字, 此站点似乎非常有趣且易于使用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.