diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
new file mode 100644
index 18fcb0c..a5edb4b
*** a/src/interfaces/libpq/fe-connect.c
--- b/src/interfaces/libpq/fe-connect.c
*************** ldapServiceLookup(const char *purl, PQco
*** 3511,3522 ****
  	}
  
  	/*
! 	 * 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;
--- 3511,3534 ----
  	}
  
  	/*
! 	 * 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;
+ 	}
+ 
+ 	/* anonymous bind */
  	if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
  	{
! 		/* error or network timeout */
  		free(url);
  		ldap_unbind(ld);
  		return 2;
*************** ldapServiceLookup(const char *purl, PQco
*** 3527,3544 ****
  	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;
  	if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
--- 3539,3572 ----
  	if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
  		res == NULL)
  	{
+ 		/* error or timeout */
  		if (res != NULL)
  			ldap_msgfree(res);
  		free(url);
  		ldap_unbind(ld);
  		return 2;
  	}
  	ldap_msgfree(res);
  
+ 	/* 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
+ 	/* the nonstandard ldap_connect function performs an anonymous bind */
+ 	if (ldap_connect(ld, &time) != LDAP_SUCCESS)
+ 	{
+ 		/* error or timeout in ldap_connect */
+ 		free(url);
+ 		ldap_unbind(ld);
+ 		return 2;
+ 	}
+ #endif
+ 
  	/* search */
  	res = NULL;
  	if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
