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

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


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.