开发者

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

开发者 https://www.devze.com 2023-02-04 16:26 出处:网络
I\'m trying to make a Linux server running in Windows. Socket and file descriptor are treated the same in Linux.

I'm trying to make a Linux server running in Windows.

Socket and file descriptor are treated the same in Linux. 开发者_JS百科Some system api are avaliable for both socket and file descriptor.

However, I deal with socket by Winsock and HANDLE(file descriptor) by WIN API.

So I need to know an integer is a socket or a HANDLE.

Now here is the question:

Would the return value from socket() and open() be the same in Windows?

If they are always different, I can write my own socket() and open() to wrap system's one. and record the return value from system's api whether the integer is a socket or 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. 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().

open() returns CRT file descriptors which is different from the Win32 handle. You can create a CRT file descriptor using _open_osfhandle(). 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.


Would the return value from socket() and open() be the same in Windows?

Socket handles in Windows are allocated by the WINSOCK subsystem which isn't part of the file system at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消