diff --git a/include/ac/errno.h b/include/ac/errno.h
index 48fa87da6230eea3c2ecee82615e6918d86bd834..a60ef0abfbde0135391f08959841525bc8014a67 100644
--- a/include/ac/errno.h
+++ b/include/ac/errno.h
@@ -28,6 +28,10 @@ extern char     *sys_errlist[];
 #endif
 #endif
     
+#if !defined( EWOULDBLOCK ) && defined( WSAEWOULDBLOCK )
+#define EWOULDBLOCK WSAEWOULDBLOCK
+#endif
+
 /* use _POSIX_VERSION for POSIX.1 code */
 
 #endif /* _AC_ERRNO_H */
diff --git a/servers/slapd/connection.c b/servers/slapd/connection.c
index 25bf3d468c5f2d37b308389955d1b3984e83101e..e7acc3e9cefd482f4a352529627a698216858e07 100644
--- a/servers/slapd/connection.c
+++ b/servers/slapd/connection.c
@@ -10,10 +10,6 @@
 
 #include "slap.h"
 
-#ifdef HAVE_WINSOCK
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#endif
-
 /* protected by connections_mutex */
 static ldap_pvt_thread_mutex_t connections_mutex;
 static Connection *connections = NULL;
diff --git a/servers/slapd/daemon.c b/servers/slapd/daemon.c
index 05a38dbd9c5d67adf18747cc5dee31b93b8c55a5..4c8e50629bdf17a7c1cf8197be46510597a22976 100644
--- a/servers/slapd/daemon.c
+++ b/servers/slapd/daemon.c
@@ -166,15 +166,6 @@ set_socket( struct sockaddr_in *addr )
 	}
 #endif	/* !FD_SETSIZE */
 
-#ifdef HAVE_WINSOCK
-	{
-		WORD    vers = MAKEWORD( 2, 0);
-		int     err;
-		WSADATA wsaData;
-		err = WSAStartup( vers, &wsaData );
-	}
-#endif
-
 	if( addr != NULL ) {
 		int	tmp;
 
@@ -598,23 +589,32 @@ slapd_daemon_task(
 
 int slapd_daemon( int inetd, int tcps )
 {
-	int status;
+	int rc;
 	int *args = ch_malloc( sizeof( int[2] ) );
 	args[0] = inetd;
 	args[1] = tcps;
 
+#ifdef HAVE_WINSOCK
+	{
+		WORD    vers = MAKEWORD( 2, 0);
+		int     err;
+		WSADATA wsaData;
+		err = WSAStartup( vers, &wsaData );
+	}
+#endif
+
 	connections_init();
 
 #define SLAPD_LISTENER_THREAD 1
 #if SLAPD_LISTENER_THREAD
 	/* listener as a separate THREAD */
-	status = ldap_pvt_thread_create( &listener_tid,
+	rc = ldap_pvt_thread_create( &listener_tid,
 		0, slapd_daemon_task, args );
 
-	if ( status != 0 ) {
+	if ( rc != 0 ) {
 		Debug( LDAP_DEBUG_ANY,
-		    "listener ldap_pvt_thread_create failed (%d)\n", status, 0, 0 );
-		return -1;
+		    "listener ldap_pvt_thread_create failed (%d)\n", rc, 0, 0 );
+		goto destory;
 	}
 
 	/* wait for the listener thread to complete */
@@ -625,8 +625,16 @@ int slapd_daemon( int inetd, int tcps )
 	slapd_daemon_task( args );
 #endif
 
+	rc = 0;
+
+destory:
 	connections_destroy();
-	return 0;
+
+#ifdef HAVE_WINSOCK
+    WSACleanup( );
+#endif
+
+	return rc;
 }
 
 void
diff --git a/servers/slapd/result.c b/servers/slapd/result.c
index 66ffd1346f3073be59199fc24d2aa18e587e792d..12bb7c07db8edbb0d6f174352cffb583728a8e47 100644
--- a/servers/slapd/result.c
+++ b/servers/slapd/result.c
@@ -13,10 +13,6 @@
 
 #include "slap.h"
 
-#ifdef HAVE_WINSOCK
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#endif
-
 static void
 send_ldap_result2(
     Connection	*conn,