Is it safe to cast SOCKET to int under Win64?

The simple answer to this question is no. Take a look at the description of SOCKET values on MSDN [1]:

Windows Sockets handles have no restrictions, other than that the value INVALID_SOCKET is not a valid socket. Socket handles may take any value in the range 0 to INVALID_SOCKET–1.

So clearly, the API allows all values in the range [0, 2^64 – 1) on 64-bit Windows. And if the API ever returned a value greater than 2^32 – 1, assigning it to an int would result in handle truncation. Also have a look at the description of the return value from the socket() function [2]:

If no error occurs, socket returns a descriptor referencing the new socket.

Notice that it most emphatically does not promise to return a kernel handle. This makes any discussion about the possible values for kernel handles moot.

All that being said, as of this writing, the socket() function really does return a kernel handle (or something indistinguishable from a kernel handle) [3] and kernel handles really are limited to 32-bits [4]. But keep in mind that Microsoft could change any of these things tomorrow without breaking their interface contracts.

However, since a doubtless large number of applications have taken a dependency on these particular implementation details (and more importantly, so has OpenSSL), Microsoft would likely think twice about making any breaking changes. So go ahead and cast a SOCKET to an int. Just keep in mind that this an inherently dangerous, bad practice, and is never justifiable in the name of expediency.

  1. http://msdn.microsoft.com/en-us/library/windows/desktop/ms740516(v=vs.85).aspx
  2. http://msdn.microsoft.com/en-us/library/windows/desktop/ms740506(v=vs.85).aspx
  3. http://msdn.microsoft.com/en-us/library/windows/desktop/ms742295(v=vs.85).aspx
  4. http://msdn.microsoft.com/en-us/library/windows/desktop/aa384267(v=vs.85).aspx

Edit (2018-01-29)

Since this topic still seems to be of some interest, it’s worth pointing out that it’s quite easy to write portable sockets code in C++11 without resorting to questionable type casts:

using socket_t = decltype(socket(0, 0, 0));

socket_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)