简体   繁体   中英

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

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

Socket and file descriptor are treated the same in Linux. 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.

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