@@ -1632,8 +1632,23 @@ PQconnectPoll(PGconn *conn)
16321632 conn -> raddr .salen = addr_cur -> ai_addrlen ;
16331633
16341634 /* Open a socket */
1635- conn -> sock = socket (addr_cur -> ai_family , SOCK_STREAM , 0 );
1636- if (conn -> sock < 0 )
1635+ {
1636+ /*
1637+ * While we use 'pgsocket' as the socket type in the
1638+ * backend, we use 'int' for libpq socket values.
1639+ * This requires us to map PGINVALID_SOCKET to -1
1640+ * on Windows.
1641+ * See http://msdn.microsoft.com/en-us/library/windows/desktop/ms740516%28v=vs.85%29.aspx
1642+ */
1643+ pgsocket sock = socket (addr_cur -> ai_family , SOCK_STREAM , 0 );
1644+ #ifdef WIN32
1645+ if (sock == PGINVALID_SOCKET )
1646+ conn -> sock = -1 ;
1647+ else
1648+ #endif
1649+ conn -> sock = sock ;
1650+ }
1651+ if (conn -> sock == -1 )
16371652 {
16381653 /*
16391654 * 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;
@@ -5300,6 +5315,15 @@ PQerrorMessage(const PGconn *conn)
53005315 return conn -> errorMessage .data ;
53015316}
53025317
5318+ /*
5319+ * In Windows, socket values are unsigned, and an invalid socket value
5320+ * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
5321+ * warning). Ideally we would return an unsigned value for PQsocket() on
5322+ * Windows, but that would cause the function's return value to differ from
5323+ * Unix, so we just return -1 for invalid sockets.
5324+ * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
5325+ * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
5326+ */
53035327int
53045328PQsocket (const PGconn * conn )
53055329{
0 commit comments