简体   繁体   English

Windows中的socket和HANDLE有什么区别?

[英]What's the difference between socket and HANDLE in Windows?

I'm trying to make a Linux server running in Windows. 我正在尝试在Windows中运行Linux服务器。

Socket and file descriptor are treated the same in Linux. 在Linux中,套接字和文件描述符的处理方式相同。 Some system api are avaliable for both socket and file descriptor. 某些系统api可用于套接字和文件描述符。

However, I deal with socket by Winsock and HANDLE(file descriptor) by WIN API. 但是,我通过WIN API处理Winsock和HANDLE(文件描述符)的socket。

So I need to know an integer is a socket or a HANDLE. 所以我需要知道一个整数是一个套接字或一个HANDLE。

Now here is the question: 现在问题是:

Would the return value from socket() and open() be the same in Windows? 在Windows中,socket()和open()的返回值是否相同?

If they are always different, I can write my own socket() and open() to wrap system's one. 如果它们总是不同,我可以编写自己的socket()和open()来包装系统的一个。 and record the return value from system's api whether the integer is a socket or HANDLE. 并记录系统api的返回值,无论整数是套接字还是HANDLE。

If they will be the same, I have no idea to deal with it. 如果它们是相同的,我不知道如何处理它。

Socket handles are Win32 (NT kernel) handles so you can, for example, use ReadFile, or WriteFile on them. 套接字句柄是Win32(NT内核)句柄,因此您可以在它们上使用ReadFile或WriteFile。 There is also user-mode state associated with the handle which is maintained by Winsock which is why you need to use closesocket() instead of CloseHandle(). 还有与Winsock维护的句柄相关联的用户模式状态,这就是为什么你需要使用closesocket()而不是CloseHandle()。

open() returns CRT file descriptors which is different from the Win32 handle. open()返回与Win32句柄不同的CRT文件描述符。 You can create a CRT file descriptor using _open_osfhandle() . 您可以使用_open_osfhandle()创建CRT文件描述符。 But this is not recommened for sockets because you cannot close the file in a clean way. 但是不推荐使用套接字,因为您无法以干净的方式关闭文件。 You either use close() which will leak the Winsock user-mode state, or closesocket() which will leak the CRT descriptor. 您可以使用close()来泄漏Winsock用户模式状态,也可以使用closesocket()来泄漏CRT描述符。

Would the return value from socket() and open() be the same in Windows? 在Windows中,socket()和open()的返回值是否相同?

Socket handles in Windows are allocated by the WINSOCK subsystem which isn't part of the file system at all. Windows中的套接字句柄由WINSOCK子系统分配,该子系统根本不属于文件系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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