@@ -1631,8 +1631,23 @@ PQconnectPoll(PGconn *conn)
16311631 conn -> raddr .salen = addr_cur -> ai_addrlen ;
16321632
16331633 /* Open a socket */
1634- conn -> sock = socket (addr_cur -> ai_family , SOCK_STREAM , 0 );
1635- if (conn -> sock < 0 )
1634+ {
1635+ /*
1636+ * While we use 'pgsocket' as the socket type in the
1637+ * backend, we use 'int' for libpq socket values.
1638+ * This requires us to map PGINVALID_SOCKET to -1
1639+ * on Windows.
1640+ * See http://msdn.microsoft.com/en-us/library/windows/desktop/ms740516%28v=vs.85%29.aspx
1641+ */
1642+ pgsocket sock = socket (addr_cur -> ai_family , SOCK_STREAM , 0 );
1643+ #ifdef WIN32
1644+ if (sock == PGINVALID_SOCKET )
1645+ conn -> sock = -1 ;
1646+ else
1647+ #endif
1648+ conn -> sock = sock ;
1649+ }
1650+ if (conn -> sock == -1 )
16361651 {
16371652 /*
16381653 * ignore socket() failure if we have more addresses
@@ -3136,7 +3151,7 @@ internal_cancel(SockAddr *raddr, int be_pid, int be_key,
31363151 char * errbuf , int errbufsize )
31373152{
31383153 int save_errno = SOCK_ERRNO ;
3139- int tmpsock = -1 ;
3154+ pgsocket tmpsock = PGINVALID_SOCKET ;
31403155 char sebuf [256 ];
31413156 int maxlen ;
31423157 struct
@@ -3149,7 +3164,7 @@ internal_cancel(SockAddr *raddr, int be_pid, int be_key,
31493164 * We need to open a temporary connection to the postmaster. Do this with
31503165 * only kernel calls.
31513166 */
3152- if ((tmpsock = socket (raddr -> addr .ss_family , SOCK_STREAM , 0 )) < 0 )
3167+ if ((tmpsock = socket (raddr -> addr .ss_family , SOCK_STREAM , 0 )) == PGINVALID_SOCKET )
31533168 {
31543169 strlcpy (errbuf , "PQcancel() -- socket() failed: " , errbufsize );
31553170 goto cancel_errReturn ;
@@ -3220,7 +3235,7 @@ internal_cancel(SockAddr *raddr, int be_pid, int be_key,
32203235 maxlen );
32213236 strcat (errbuf , "\n" );
32223237 }
3223- if (tmpsock >= 0 )
3238+ if (tmpsock != PGINVALID_SOCKET )
32243239 closesocket (tmpsock );
32253240 SOCK_ERRNO_SET (save_errno );
32263241 return FALSE;
@@ -5281,6 +5296,15 @@ PQerrorMessage(const PGconn *conn)
52815296 return conn -> errorMessage .data ;
52825297}
52835298
5299+ /*
5300+ * In Windows, socket values are unsigned, and an invalid socket value
5301+ * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
5302+ * warning). Ideally we would return an unsigned value for PQsocket() on
5303+ * Windows, but that would cause the function's return value to differ from
5304+ * Unix, so we just return -1 for invalid sockets.
5305+ * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
5306+ * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
5307+ */
52845308int
52855309PQsocket (const PGconn * conn )
52865310{
0 commit comments