diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
new file mode 100644
index 18fcb0c..e2ff092
*** a/src/interfaces/libpq/fe-connect.c
--- b/src/interfaces/libpq/fe-connect.c
*************** ldapServiceLookup(const char *purl, PQco
*** 3363,3369 ****
  	int			port = LDAP_DEF_PORT,
  				scope,
  				rc,
- 				msgid,
  				size,
  				state,
  				oldstate,
--- 3363,3368 ----
*************** ldapServiceLookup(const char *purl, PQco
*** 3511,3543 ****
  	}
  
  	/*
! 	 * Initialize connection to the server.  We do an explicit bind because we
! 	 * want to return 2 if the bind fails.
  	 */
! 	if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
  	{
- 		/* error in ldap_simple_bind() */
  		free(url);
  		ldap_unbind(ld);
! 		return 2;
  	}
! 
! 	/* wait some time for the connection to succeed */
! 	res = NULL;
! 	if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
! 		res == NULL)
  	{
! 		if (res != NULL)
  		{
! 			/* timeout */
! 			ldap_msgfree(res);
  		}
! 		/* error in ldap_result() */
  		free(url);
  		ldap_unbind(ld);
  		return 2;
  	}
! 	ldap_msgfree(res);
  
  	/* search */
  	res = NULL;
--- 3510,3558 ----
  	}
  
  	/*
! 	 * Perform an explicit anonymous bind.
! 	 * This is not necessary in principle, but we want to set a timeout
! 	 * of PGLDAP_TIMEOUT seconds and return 2 if the connection fails.
! 	 * Unfortunately there is no standard conforming way to do that.
  	 */
! #ifdef HAVE_LIBLDAP
! 	/* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
! 	if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
  	{
  		free(url);
  		ldap_unbind(ld);
! 		return 3;
  	}
! 	else
  	{
! 		/* anonymous bind */
! 		if (ldap_simple_bind_s(ld, NULL, NULL) != LDAP_SUCCESS)
  		{
! 			/* error or timeout in ldap_simple_bind_s */
! 			free(url);
! 			ldap_unbind(ld);
! 			return 2;
  		}
! 	}
! 
! 	/* reset timeout */
! 	time.tv_sec = -1;
! 	if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
! 	{
! 		free(url);
! 		ldap_unbind(ld);
! 		return 3;
! 	}
! #else
! 	/* On Windows, we have to use the nonstandard ldap_connect function */
! 	if (ldap_connect(ld, &time) != LDAP_SUCCESS)
! 	{
! 		/* error or timeout in ldap_connect */
  		free(url);
  		ldap_unbind(ld);
  		return 2;
  	}
! #endif
  
  	/* search */
  	res = NULL;
