views:

166

answers:

2

I’m working on a Windows port of a POSIX C++ program.

The problem is that standard POSIX functions like accept() or bind() expect an ‘int’ as the first parameter while its WinSock counterparts use ‘SOCKET’.
When compiled for 32-bit everything is fine, because both are 32bit, but under Win64 SOCKET is 64 bit and int remains 32 bit and it generates a lot of compiler warning like this:

warning C4244: '=' : conversion from 'SOCKET' to 'int', possible loss of data

I tried to work around the issue by using a typedef:


#ifdef _WIN32
 typedef SOCKET sock_t;
#else
 typedef int sock_t;
#endif

and replacing ‘int’s with sock_t at the appropriate places.

This was fine until I reached a part of the code which calls OpenSSL APIs.
As it turned out OpenSSL uses ints for sockets even on Win64. That seemed really strange, so I started searching for an answer, but the only thing I found was an old post on the openssl-dev mailing list which refered to a comment e_os.h:


/*
 * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because
 * the value constitutes an index in per-process table of limited size
 * and not a real pointer.
 */

So my question is:
is it really safe to cast SOCKET to int?

I’d like to see some kind of documentation which proves that values for SOCKET can't be larger than 2^32.

Thanks in advance!
Ryck

A: 
/*
 * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because
 * the value constitutes an index in per-process table of limited size
 * and not a real pointer.
 */

This comment is correct. SOCKET = File handle on Windows NT series. I've never seen a 9x series 64 bit so there should be nothing to worry about.

Joshua
+3  A: 

This post seems by the to be repeating the information on kernel objects at msdn:

Kernel object handles are process specific. That is, a process must either create the object or open an existing object to obtain a kernel object handle. The per-process limit on kernel handles is 2^24.

The thread goes on to cite Windows Internals by Russinovich and Solomon as a source for the high bits being zero.

Pete Kirkham
Thanks Pete!That’s exactly what I was looking for.Here’s a relevant post on Mark Russinovich's blog:http://blogs.technet.com/markrussinovich/archive/2009/09/29/3283844.aspx
Ryck
+1 for the multiple links
paercebal