summaryrefslogtreecommitdiff
path: root/src/network/core/address.cpp
diff options
context:
space:
mode:
authorrubidium <rubidium@openttd.org>2009-04-02 23:59:43 +0000
committerrubidium <rubidium@openttd.org>2009-04-02 23:59:43 +0000
commitc7b6469dabe5018775d075bee0a5293175024b42 (patch)
tree343b43841f480cbd2ab50df10adc949dbd3b954e /src/network/core/address.cpp
parent521bf687eef36e7c06d09ee610134eb21fed69a9 (diff)
downloadopenttd-c7b6469dabe5018775d075bee0a5293175024b42.tar.xz
(svn r15920) -Codechange: make the (TCP) connecting less AF dependent.
Diffstat (limited to 'src/network/core/address.cpp')
-rw-r--r--src/network/core/address.cpp40
1 files changed, 40 insertions, 0 deletions
diff --git a/src/network/core/address.cpp b/src/network/core/address.cpp
index 888625dc1..28ab98887 100644
--- a/src/network/core/address.cpp
+++ b/src/network/core/address.cpp
@@ -10,6 +10,7 @@
#include "config.h"
#include "host.h"
#include "../../string_func.h"
+#include "../../debug.h"
const char *NetworkAddress::GetHostname()
{
@@ -62,4 +63,43 @@ const sockaddr_storage *NetworkAddress::GetAddress()
return &this->address;
}
+SOCKET NetworkAddress::Connect()
+{
+ DEBUG(net, 1, "Connecting to %s", this->GetAddressAsString());
+
+ struct addrinfo *ai;
+ struct addrinfo hints;
+ memset(&hints, 0, sizeof (hints));
+ hints.ai_flags = AI_ADDRCONFIG;
+ hints.ai_socktype = SOCK_STREAM;
+
+ /* The port needs to be a string. Six is enough to contain all characters + '\0'. */
+ char port_name[6];
+ seprintf(port_name, lastof(port_name), "%u", this->GetPort());
+
+ int e = getaddrinfo(this->GetHostname(), port_name, &hints, &ai);
+ if (e != 0) {
+ DEBUG(net, 0, "getaddrinfo failed: %s", gai_strerror(e));
+ return false;
+ }
+
+ SOCKET sock = INVALID_SOCKET;
+ for (struct addrinfo *runp = ai; runp != NULL; runp = runp->ai_next) {
+ sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
+ if (sock == INVALID_SOCKET) continue;
+
+ if (!SetNoDelay(sock)) DEBUG(net, 1, "Setting TCP_NODELAY failed");
+
+ if (connect(sock, runp->ai_addr, runp->ai_addrlen) != 0) continue;
+
+ /* Connection succeeded */
+ if (!SetNonBlocking(sock)) DEBUG(net, 0, "Setting non-blocking mode failed");
+
+ break;
+ }
+ freeaddrinfo (ai);
+
+ return sock;
+}
+
#endif /* ENABLE_NETWORK */