From be6317e62a479ae3d015756728fcfcf0a718275d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com>
Date: Wed, 1 Apr 2015 14:36:38 -0400
Subject: [PATCH] fix build for Win32

---
 configure.ac                | 27 +++++++++++++++++++++++++++
 include/opendht/dhtrunner.h |  6 ++----
 src/dhtrunner.cpp           | 24 ++++++++++++++++++++++++
 3 files changed, 53 insertions(+), 4 deletions(-)

diff --git a/configure.ac b/configure.ac
index 6e763054..7af9af75 100644
--- a/configure.ac
+++ b/configure.ac
@@ -3,6 +3,7 @@ AC_CONFIG_AUX_DIR(ac)
 AM_INIT_AUTOMAKE([foreign])
 AC_CONFIG_HEADERS([config.h])
 AC_CONFIG_MACRO_DIR([m4])
+AC_CANONICAL_HOST
 
 AC_ARG_ENABLE([debug], AS_HELP_STRING([--enable-debug], [Build in debug mode, adds stricter warnings, disables optimization]))
 AS_IF([test "x$enable_debug" = "xyes"],
@@ -13,6 +14,32 @@ AC_PROG_CC
 AC_PROG_CXX
 AM_PROG_AR
 
+case "${host_os}" in
+  "")
+    SYS=unknown
+    ;;
+  linux*)
+    SYS=linux
+    ;;
+  darwin*)
+    SYS=darwin
+    ;;
+  mingw32*)
+    SYS=mingw32
+    AC_DEFINE([_POSIX_SOURCE], [1], [IEEE Std 1003.1.])
+    AC_DEFINE([_POSIX_C_SOURCE], [200809L], [IEEE Std 1003.1.])
+    AC_DEFINE([_XOPEN_SOURCE], [700], [POSIX and XPG 7th edition])
+    AC_DEFINE([_XOPEN_SOURCE_EXTENDED], [1], [XPG things and X/Open Unix extensions.])
+    AC_DEFINE([_BSD_SOURCE], [1], [ISO C, POSIX, and 4.3BSD things.])
+    LDFLAGS="${LDFLAGS} -lws2_32"
+    AC_SUBST(WINDOWS_ARCH)
+    AC_SUBST(PROGRAMFILES)
+    ;;
+  *)
+    SYS="${host_os}"
+    ;;
+esac
+
 LT_INIT()
 LT_LANG(C++)
 
diff --git a/include/opendht/dhtrunner.h b/include/opendht/dhtrunner.h
index 30a44c72..0cde00b1 100644
--- a/include/opendht/dhtrunner.h
+++ b/include/opendht/dhtrunner.h
@@ -54,10 +54,8 @@ class DhtRunner {
 public:
     typedef std::function<void(Dht::Status, Dht::Status)> StatusCallback;
 
-    DhtRunner() {}
-    virtual ~DhtRunner() {
-        join();
-    }
+    DhtRunner();
+    virtual ~DhtRunner();
 
     void get(InfoHash hash, Dht::GetCallback vcb, Dht::DoneCallback dcb=nullptr, Value::Filter f = Value::AllFilter());
     void get(const std::string& key, Dht::GetCallback vcb, Dht::DoneCallback dcb=nullptr, Value::Filter f = Value::AllFilter());
diff --git a/src/dhtrunner.cpp b/src/dhtrunner.cpp
index ac94f5cd..83cb9ec6 100644
--- a/src/dhtrunner.cpp
+++ b/src/dhtrunner.cpp
@@ -32,8 +32,32 @@
 
 #include <unistd.h> // close(fd)
 
+#ifndef _WIN32
+#include <sys/socket.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+
 namespace dht {
 
+DhtRunner::DhtRunner()
+{
+#ifdef _WIN32
+    WSADATA wsd;
+    if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)
+        throw DhtException("Can't initialize Winsock2");
+#endif
+}
+
+DhtRunner::~DhtRunner()
+{
+    join();
+#ifdef _WIN32
+    WSACleanup();
+#endif
+}
+
 void
 DhtRunner::run(in_port_t port, const crypto::Identity identity, bool threaded, StatusCallback cb)
 {
-- 
GitLab