From 43479ef719ea8fc6abbf654730b47c4583140508 Mon Sep 17 00:00:00 2001
From: Tobias Markmann <tm@ayena.de>
Date: Tue, 8 Nov 2016 15:29:17 +0100
Subject: Improve string to HostAddress conversion API

Previously HostAddress had a constructor which allowed
initialisation via a std::string. This initialisation can
fail and this is heavily used for checking whether a string
is a valid IP address.

This constructor is removed in this commit and replaced by
a static method HostAddress::fromString, taking a string and
returning an optional HostAddress. This clearly communicates
that the conversion can fail.

Test-Information:

./scons test=all passes on macOS 10.12.1.

Change-Id: Idaafee6f84010ce541c55f267ac77ad6ac8f02b4

diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
index 3515a0a..3b4fa83 100644
--- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
+++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp
@@ -33,8 +33,8 @@ class ComponentConnectorTest : public CppUnit::TestFixture {
 
     public:
         void setUp() {
-            host1 = HostAddress("1.1.1.1");
-            host2 = HostAddress("2.2.2.2");
+            host1 = HostAddress::fromString("1.1.1.1").get();
+            host2 = HostAddress::fromString("2.2.2.2").get();
             eventLoop = new DummyEventLoop();
             resolver = new StaticDomainNameResolver(eventLoop);
             connectionFactory = new MockConnectionFactory(eventLoop);
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
index 2975193..09b664f 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
@@ -18,7 +18,6 @@
 #include <boost/bind.hpp>
 
 #include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
 #include <Swiften/Elements/JingleS5BTransportPayload.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamServerManager.h>
@@ -140,7 +139,7 @@ void LocalJingleTransportCandidateGenerator::emitOnLocalTransportCandidatesGener
     if (options_.isDirectAllowed()) {
         // get direct candidates
         std::vector<HostAddressPort> directCandidates = s5bServerManager->getHostAddressPorts();
-        foreach(HostAddressPort addressPort, directCandidates) {
+        for(auto&& addressPort : directCandidates) {
             if (addressPort.getAddress().getRawAddress().is_v6() &&
                 addressPort.getAddress().getRawAddress().to_v6().is_link_local()) {
                 continue;
@@ -158,7 +157,7 @@ void LocalJingleTransportCandidateGenerator::emitOnLocalTransportCandidatesGener
     if (options_.isAssistedAllowed()) {
         // get assissted candidates
         std::vector<HostAddressPort> assisstedCandidates = s5bServerManager->getAssistedHostAddressPorts();
-        foreach(HostAddressPort addressPort, assisstedCandidates) {
+        for (auto&& addressPort : assisstedCandidates) {
             JingleS5BTransportPayload::Candidate candidate;
             candidate.type = JingleS5BTransportPayload::Candidate::AssistedType;
             candidate.jid = ownJID;
@@ -170,17 +169,18 @@ void LocalJingleTransportCandidateGenerator::emitOnLocalTransportCandidatesGener
     }
 
     if (options_.isProxiedAllowed() && s5bProxy->getOrDiscoverS5BProxies().is_initialized()) {
-        foreach(S5BProxyRequest::ref proxy, s5bProxy->getOrDiscoverS5BProxies().get()) {
+        for (auto&& proxy : s5bProxy->getOrDiscoverS5BProxies().get()) {
             if (proxy->getStreamHost()) { // FIXME: Added this test, because there were cases where this wasn't initialized. Investigate this. (Remko)
                 JingleS5BTransportPayload::Candidate candidate;
                 candidate.type = JingleS5BTransportPayload::Candidate::ProxyType;
                 candidate.jid = (*proxy->getStreamHost()).jid;
-                HostAddress address = (*proxy->getStreamHost()).host;
-                assert(address.isValid());
-                candidate.hostPort = HostAddressPort(address, (*proxy->getStreamHost()).port);
-                candidate.priority = 65536 * 10 + LOCAL_PREFERENCE;
-                candidate.cid = idGenerator->generateID();
-                candidates.push_back(candidate);
+                auto address = HostAddress::fromString((*proxy->getStreamHost()).host);
+                if (address) {
+                    candidate.hostPort = HostAddressPort(address.get(), (*proxy->getStreamHost()).port);
+                    candidate.priority = 65536 * 10 + LOCAL_PREFERENCE;
+                    candidate.cid = idGenerator->generateID();
+                    candidates.push_back(candidate);
+                }
             }
         }
     }
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
index 367676b..cd4cfaa 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
@@ -18,7 +18,6 @@
 #include <boost/bind.hpp>
 
 #include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
 #include <Swiften/Network/ConnectionFactory.h>
 #include <Swiften/Network/DomainNameAddressQuery.h>
@@ -37,8 +36,8 @@ SOCKS5BytestreamProxiesManager::~SOCKS5BytestreamProxiesManager() {
         proxyFinder_->stop();
     }
 
-    foreach (const ProxySessionsMap::value_type& sessionsForID, proxySessions_) {
-        foreach (const ProxyJIDClientSessionVector::value_type& session, sessionsForID.second) {
+    for (const auto& sessionsForID : proxySessions_) {
+        for (const auto& session : sessionsForID.second) {
             session.second->onSessionReady.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionsForID.first, session.first, session.second, _1));
             session.second->onFinished.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionsForID.first, session.first, session.second, _1));
         }
@@ -47,7 +46,7 @@ SOCKS5BytestreamProxiesManager::~SOCKS5BytestreamProxiesManager() {
 
 void SOCKS5BytestreamProxiesManager::addS5BProxy(S5BProxyRequest::ref proxy) {
     if (proxy) {
-        SWIFT_LOG_ASSERT(HostAddress(proxy->getStreamHost().get().host).isValid(), warning) << std::endl;
+        SWIFT_LOG_ASSERT(HostAddress::fromString(proxy->getStreamHost().get().host), warning) << std::endl;
         if (!localS5BProxies_) {
             localS5BProxies_ = std::vector<S5BProxyRequest::ref>();
         }
@@ -67,17 +66,19 @@ void SOCKS5BytestreamProxiesManager::connectToProxies(const std::string& session
     ProxyJIDClientSessionVector clientSessions;
 
     if (localS5BProxies_) {
-        foreach(S5BProxyRequest::ref proxy, localS5BProxies_.get()) {
-            std::shared_ptr<Connection> conn = connectionFactory_->createConnection();
-
-            HostAddressPort addressPort = HostAddressPort(proxy->getStreamHost().get().host, proxy->getStreamHost().get().port);
-            SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
-            std::shared_ptr<SOCKS5BytestreamClientSession> session = std::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
-            JID proxyJid = proxy->getStreamHost().get().jid;
-            clientSessions.push_back(std::pair<JID, std::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session));
-            session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1));
-            session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1));
-            session->start();
+        for (auto&& proxy : localS5BProxies_.get()) {
+            auto proxyHostAddress = HostAddress::fromString(proxy->getStreamHost().get().host);
+            if (proxyHostAddress) {
+                std::shared_ptr<Connection> conn = connectionFactory_->createConnection();
+                HostAddressPort addressPort = HostAddressPort(proxyHostAddress.get(), proxy->getStreamHost().get().port);
+                SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
+                std::shared_ptr<SOCKS5BytestreamClientSession> session = std::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
+                JID proxyJid = proxy->getStreamHost().get().jid;
+                clientSessions.push_back(std::pair<JID, std::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session));
+                session->onSessionReady.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionReady, this,sessionID, proxyJid, session, _1));
+                session->onFinished.connect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxySessionFinished, this, sessionID, proxyJid, session, _1));
+                session->start();
+            }
         }
     }
 
@@ -116,9 +117,10 @@ std::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::c
 
 void SOCKS5BytestreamProxiesManager::handleProxiesFound(std::vector<S5BProxyRequest::ref> proxyHosts) {
     proxyFinder_->onProxiesFound.disconnect(boost::bind(&SOCKS5BytestreamProxiesManager::handleProxiesFound, this, _1));
-    foreach(S5BProxyRequest::ref proxy, proxyHosts) {
+    for (auto&& proxy : proxyHosts) {
         if (proxy) {
-            if (HostAddress(proxy->getStreamHost().get().host).isValid()) {
+            auto proxyHostAddress = HostAddress::fromString(proxy->getStreamHost().get().host);
+            if (proxyHostAddress) {
                 addS5BProxy(proxy);
                 onDiscoveredProxiesChanged();
             }
@@ -146,7 +148,7 @@ void SOCKS5BytestreamProxiesManager::handleNameLookupResult(const std::vector<Ho
         }
         else {
             // generate proxy per returned address
-            foreach (const HostAddress& address, addresses) {
+            for (const auto& address : addresses) {
                 S5BProxyRequest::StreamHost streamHost = proxy->getStreamHost().get();
                 S5BProxyRequest::ref proxyForAddress = std::make_shared<S5BProxyRequest>(*proxy);
                 streamHost.host = address.toString();
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
index 33a5283..f749735 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
@@ -17,7 +17,6 @@
 #include <boost/bind.hpp>
 
 #include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamServerPortForwardingUser.h>
 #include <Swiften/FileTransfer/SOCKS5BytestreamServerResourceUser.h>
@@ -88,8 +87,8 @@ std::vector<HostAddressPort> SOCKS5BytestreamServerManager::getHostAddressPorts(
     std::vector<HostAddressPort> result;
     if (connectionServer) {
         std::vector<NetworkInterface> networkInterfaces = networkEnvironment->getNetworkInterfaces();
-        foreach (const NetworkInterface& networkInterface, networkInterfaces) {
-            foreach (const HostAddress& address, networkInterface.getAddresses()) {
+        for (const auto& networkInterface : networkInterfaces) {
+            for (const auto& address : networkInterface.getAddresses()) {
                 result.push_back(HostAddressPort(address, connectionServerPort));
             }
         }
@@ -118,7 +117,7 @@ void SOCKS5BytestreamServerManager::initialize() {
         int port;
         for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) {
             SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl;
-            connectionServer = connectionServerFactory->createConnectionServer(HostAddress("::"), port);
+            connectionServer = connectionServerFactory->createConnectionServer(HostAddress::fromString("::").get(), port);
             boost::optional<ConnectionServer::Error> error = connectionServer->tryStart();
             if (!error) {
                 break;
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
index cb43d78..290dda5 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -53,7 +53,7 @@ class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture {
     CPPUNIT_TEST_SUITE_END();
 
 public:
-    SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)) {}
+    SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress::fromString("127.0.0.1").get(), 8888)) {}
 
     void setUp() {
         crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
index 3c5e098..85ae537 100644
--- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
+++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp
@@ -44,7 +44,7 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture {
         void testConnect() {
             std::shared_ptr<LinkLocalConnector>
                     testling(createConnector("rabbithole.local", 1234));
-            querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+            querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
 
             testling->connect();
             eventLoop->processEvents();
@@ -72,7 +72,7 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture {
         void testConnect_UnableToConnect() {
             std::shared_ptr<LinkLocalConnector>
                     testling(createConnector("rabbithole.local", 1234));
-            querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+            querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
             connection->setError(Connection::ReadError);
 
             testling->connect();
@@ -92,7 +92,7 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture {
 
             testling->cancel();
             eventLoop->processEvents();
-            querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+            querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
             eventLoop->processEvents();
 
             CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state);
@@ -101,7 +101,7 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture {
         void testCancel_DuringConnect() {
             std::shared_ptr<LinkLocalConnector>
                     testling(createConnector("rabbithole.local", 1234));
-            querier->setAddress("rabbithole.local", HostAddress("192.168.1.1"));
+            querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get());
             connection->setDelayConnect();
             testling->connect();
             eventLoop->processEvents();
diff --git a/Swiften/Network/Connector.cpp b/Swiften/Network/Connector.cpp
index 37cf35d..457d8a9 100644
--- a/Swiften/Network/Connector.cpp
+++ b/Swiften/Network/Connector.cpp
@@ -30,6 +30,7 @@ void Connector::start() {
     assert(!serviceQuery);
     assert(!timer);
     queriedAllServices = false;
+    auto hostAddress = HostAddress::fromString(hostname);
     if (timeoutMilliseconds > 0) {
         timer = timerFactory->createTimer(timeoutMilliseconds);
         timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this()));
@@ -39,10 +40,10 @@ void Connector::start() {
         serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1));
         serviceQuery->run();
     }
-    else if (HostAddress(hostname).isValid()) {
+    else if (hostAddress) {
         // hostname is already a valid address; skip name lookup.
         foundSomeDNS = true;
-        addressQueryResults.push_back(HostAddress(hostname));
+        addressQueryResults.push_back(hostAddress.get());
         tryNextAddress();
     } else {
         queryAddress(hostname);
diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp
index faf2e5b..8edb136 100644
--- a/Swiften/Network/EnvironmentProxyProvider.cpp
+++ b/Swiften/Network/EnvironmentProxyProvider.cpp
@@ -50,7 +50,7 @@ HostAddressPort EnvironmentProxyProvider::getFromEnv(const char* envVarName, std
         address = address.substr(0, address.find(':'));
     }
 
-    return HostAddressPort(HostAddress(address), port);
+    return HostAddressPort(HostAddress::fromString(address).get_value_or(HostAddress()), port);
 }
 
 }
diff --git a/Swiften/Network/HostAddress.cpp b/Swiften/Network/HostAddress.cpp
index 63cd3f2..6eca80b 100644
--- a/Swiften/Network/HostAddress.cpp
+++ b/Swiften/Network/HostAddress.cpp
@@ -20,14 +20,6 @@ namespace Swift {
 HostAddress::HostAddress() {
 }
 
-HostAddress::HostAddress(const std::string& address) {
-    boost::system::error_code errorCode;
-    address_ = boost::asio::ip::address::from_string(address, errorCode);
-    if (errorCode) {
-        SWIFT_LOG(warning) << "error: " << errorCode.message() << " (" << errorCode << ")" << ", " << "address: " << address << std::endl;
-    }
-}
-
 HostAddress::HostAddress(const unsigned char* address, size_t length) {
     assert(length == 4 || length == 16);
     if (length == 4) {
@@ -69,4 +61,14 @@ bool HostAddress::isLocalhost() const {
     return address_ == localhost4 || address_ == localhost6;
 }
 
+boost::optional<HostAddress> HostAddress::fromString(const std::string& addressString) {
+    boost::optional<HostAddress> hostAddress;
+    boost::system::error_code errorCode;
+    boost::asio::ip::address address = boost::asio::ip::address::from_string(addressString, errorCode);
+    if (!errorCode) {
+        hostAddress = HostAddress(address);
+    }
+    return hostAddress;
+}
+
 }
diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h
index 00fe9bf..e4ddffb 100644
--- a/Swiften/Network/HostAddress.h
+++ b/Swiften/Network/HostAddress.h
@@ -3,11 +3,13 @@
  * All rights reserved.
  * See the COPYING file for more information.
  */
+
 #pragma once
 
 #include <string>
 
 #include <boost/asio/ip/address.hpp>
+#include <boost/optional.hpp>
 
 #include <Swiften/Base/API.h>
 
@@ -15,7 +17,6 @@ namespace Swift {
     class SWIFTEN_API HostAddress {
         public:
             HostAddress();
-            HostAddress(const std::string&);
             HostAddress(const unsigned char* address, size_t length);
             HostAddress(const boost::asio::ip::address& address);
 
@@ -29,6 +30,8 @@ namespace Swift {
             bool isValid() const;
             bool isLocalhost() const;
 
+            static boost::optional<HostAddress> fromString(const std::string& addressString);
+
         private:
             boost::asio::ip::address address_;
     };
diff --git a/Swiften/Network/MacOSXProxyProvider.cpp b/Swiften/Network/MacOSXProxyProvider.cpp
index acea480..232fc60 100644
--- a/Swiften/Network/MacOSXProxyProvider.cpp
+++ b/Swiften/Network/MacOSXProxyProvider.cpp
@@ -16,9 +16,10 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <iostream>
-#include <boost/numeric/conversion/cast.hpp>
 #include <utility>
 
+#include <boost/numeric/conversion/cast.hpp>
+
 #ifndef SWIFTEN_PLATFORM_IPHONE
 #include <SystemConfiguration/SystemConfiguration.h>
 #endif
@@ -67,7 +68,7 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl
             }
 
             if(host != "" && port != 0) {
-                ret = HostAddressPort(HostAddress(host), port);
+                ret = HostAddressPort(HostAddress::fromString(host).get(), port);
             }
         }
     }
diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp
index d63b69e..dbe8bcd 100644
--- a/Swiften/Network/MiniUPnPInterface.cpp
+++ b/Swiften/Network/MiniUPnPInterface.cpp
@@ -69,7 +69,7 @@ boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() {
         return boost::optional<HostAddress>();
     }
     else {
-        return HostAddress(std::string(externalIPAddress));
+        return HostAddress::fromString(std::string(externalIPAddress));
     }
 }
 
diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp
index 16bab0d..aa6c4d2 100644
--- a/Swiften/Network/ProxiedConnection.cpp
+++ b/Swiften/Network/ProxiedConnection.cpp
@@ -26,7 +26,7 @@ ProxiedConnection::ProxiedConnection(
             timerFactory_(timerFactory),
             proxyHost_(proxyHost),
             proxyPort_(proxyPort),
-            server_(HostAddressPort(HostAddress("0.0.0.0"), 0)) {
+            server_(HostAddressPort(HostAddress::fromString("0.0.0.0").get(), 0)) {
     connected_ = false;
 }
 
diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
index 8dbd09e..5d6fedd 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp
@@ -69,7 +69,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture {
             boshDataRead.clear();
             boshDataWritten.clear();
             resolver = new StaticDomainNameResolver(eventLoop);
-            resolver->addAddress(to, HostAddress("127.0.0.1"));
+            resolver->addAddress(to, HostAddress::fromString("127.0.0.1").get());
             timerFactory = new DummyTimerFactory();
         }
 
@@ -234,7 +234,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture {
 
         void testSession() {
             to = "prosody.doomsong.co.uk";
-            resolver->addAddress("prosody.doomsong.co.uk", HostAddress("127.0.0.1"));
+            resolver->addAddress("prosody.doomsong.co.uk", HostAddress::fromString("127.0.0.1").get());
             path = "/http-bind/";
             boshURL = URL("http", to, 5280, path);
 
diff --git a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
index a791e96..99dd462 100644
--- a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp
@@ -193,7 +193,7 @@ class BOSHConnectionTest : public CppUnit::TestFixture {
     private:
 
         BOSHConnection::ref createTestling() {
-            resolver->addAddress("wonderland.lit", HostAddress("127.0.0.1"));
+            resolver->addAddress("wonderland.lit", HostAddress::fromString("127.0.0.1").get());
             Connector::ref connector = Connector::create("wonderland.lit", 5280, boost::optional<std::string>(), resolver, connectionFactory, timerFactory);
             BOSHConnection::ref c = BOSHConnection::create(URL("http", "wonderland.lit", 5280, "/http-bind"), connector, &parserFactory, tlsContextFactory, TLSOptions());
             c->onConnectFinished.connect(boost::bind(&BOSHConnectionTest::handleConnectFinished, this, _1));
diff --git a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
index 3fad433..2d78cd7 100644
--- a/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ChainedConnectorTest.cpp
@@ -34,7 +34,7 @@ class ChainedConnectorTest : public CppUnit::TestFixture {
     public:
         void setUp() {
             error.reset();
-            host = HostAddressPort(HostAddress("1.1.1.1"), 1234);
+            host = HostAddressPort(HostAddress::fromString("1.1.1.1").get(), 1234);
             eventLoop = new DummyEventLoop();
             resolver = new StaticDomainNameResolver(eventLoop);
             resolver->addXMPPClientService("foo.com", host);
diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp
index 20ad68d..8524439 100644
--- a/Swiften/Network/UnitTest/ConnectorTest.cpp
+++ b/Swiften/Network/UnitTest/ConnectorTest.cpp
@@ -43,9 +43,9 @@ class ConnectorTest : public CppUnit::TestFixture {
 
     public:
         void setUp() {
-            host1 = HostAddressPort(HostAddress("1.1.1.1"), 1234);
-            host2 = HostAddressPort(HostAddress("2.2.2.2"), 2345);
-            host3 = HostAddressPort(HostAddress("3.3.3.3"), 5222);
+            host1 = HostAddressPort(HostAddress::fromString("1.1.1.1").get(), 1234);
+            host2 = HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345);
+            host3 = HostAddressPort(HostAddress::fromString("3.3.3.3").get(), 5222);
             eventLoop = new DummyEventLoop();
             resolver = new StaticDomainNameResolver(eventLoop);
             connectionFactory = new MockConnectionFactory(eventLoop);
@@ -122,8 +122,8 @@ class ConnectorTest : public CppUnit::TestFixture {
         void testConnect_FirstAddressHostFails() {
             Connector::ref testling(createConnector());
 
-            HostAddress address1("1.1.1.1");
-            HostAddress address2("2.2.2.2");
+            auto address1 = HostAddress::fromString("1.1.1.1").get();
+            auto address2 = HostAddress::fromString("2.2.2.2").get();
             resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
             resolver->addAddress("host-foo.com", address1);
             resolver->addAddress("host-foo.com", address2);
@@ -245,10 +245,10 @@ class ConnectorTest : public CppUnit::TestFixture {
             Connector::ref testling(createConnector());
             testling->setTimeoutMilliseconds(10);
 
+            auto address2 = HostAddress::fromString("2.2.2.2").get();
+
             resolver->addXMPPClientService("foo.com", "host-foo.com", 1234);
-            HostAddress address1("1.1.1.1");
-            resolver->addAddress("host-foo.com", address1);
-            HostAddress address2("2.2.2.2");
+            resolver->addAddress("host-foo.com", HostAddress::fromString("1.1.1.1").get());
             resolver->addAddress("host-foo.com", address2);
 
             connectionFactory->isResponsive = false;
diff --git a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
index 232847b..1a160b7 100644
--- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
@@ -18,7 +18,6 @@
 
 #include <Swiften/Base/Algorithm.h>
 #include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
 #include <Swiften/EventLoop/DummyEventLoop.h>
 #include <Swiften/Network/Connection.h>
 #include <Swiften/Network/ConnectionFactory.h>
@@ -65,8 +64,7 @@ namespace {
 
                 int statusCode = boost::lexical_cast<int>(statusLineFields[1]);
                 if (statusCode == 407) {
-                    typedef std::pair<std::string, std::string> StrPair;
-                    foreach (const StrPair& field, response) {
+                    for (const auto& field : response) {
                         if (to_lower(field.first) == to_lower("Proxy-Authenticate")) {
                             if (field.second.size() >= 6 && field.second.substr(0, 6) == " NTLM ") {
                                 filterResponseReturn.push_back(std::pair<std::string, std::string>("Proxy-Authorization", "NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABIAEgBIAAAABgAGAFoAAAASABIVNTUAADAAYAAAABAAEACiAAAANYKI4gUBKAoAAAAPTABBAEIAUwBNAE8ASwBFADMAXwBxAGEATABBAEIAUwBNAE8ASwBFADMA0NKq8HYYhj8AAAAAAAAAAAAAAAAAAAAAOIiih3mR+AkyM4r99sy1mdFonCu2ILODro1WTTrJ4b4JcXEzUBA2Ig=="));
@@ -108,8 +106,8 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
         void setUp() {
             proxyHost = "doo.bah";
             proxyPort = 1234;
-            proxyHostAddress = HostAddressPort(HostAddress("1.1.1.1"), proxyPort);
-            host = HostAddressPort(HostAddress("2.2.2.2"), 2345);
+            proxyHostAddress = HostAddressPort(HostAddress::fromString("1.1.1.1").get(), proxyPort);
+            host = HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345);
             eventLoop = new DummyEventLoop();
             resolver = new StaticDomainNameResolver(eventLoop);
             resolver->addAddress(proxyHost, proxyHostAddress.getAddress());
@@ -148,14 +146,14 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
         void testConnect_SendsConnectRequest() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
 
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n\r\n"), connectionFactory->connections[0]->dataWritten);
         }
 
         void testConnect_ReceiveConnectResponse() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
             eventLoop->processEvents();
@@ -167,7 +165,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testConnect_ReceiveConnectChunkedResponse() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 "));
             eventLoop->processEvents();
@@ -182,7 +180,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testConnect_ReceiveMalformedConnectResponse() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("FLOOP"));
             eventLoop->processEvents();
@@ -194,7 +192,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testConnect_ReceiveErrorConnectResponse() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 401 Unauthorized\r\n\r\n"));
             eventLoop->processEvents();
@@ -206,7 +204,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testConnect_ReceiveDataAfterConnect() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
             eventLoop->processEvents();
 
@@ -217,7 +215,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testWrite_AfterConnect() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
             eventLoop->processEvents();
             connectionFactory->connections[0]->dataWritten.clear();
@@ -229,7 +227,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testDisconnect_AfterConnectRequest() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             testling->disconnect();
 
@@ -240,7 +238,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
 
         void testDisconnect_AfterConnect() {
             HTTPConnectProxiedConnection::ref testling(createTestling());
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
             connectionFactory->connections[0]->onDataRead(createSafeByteArrayRef("HTTP/1.0 200 Connection established\r\n\r\n"));
             eventLoop->processEvents();
 
@@ -257,7 +255,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
             std::shared_ptr<ExampleHTTPTrafficFilter> httpTrafficFilter = std::make_shared<ExampleHTTPTrafficFilter>();
 
             testling->setHTTPTrafficFilter(httpTrafficFilter);
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             // set a default response so the server response is answered by the traffic filter
             httpTrafficFilter->filterResponseReturn.clear();
@@ -298,7 +296,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture {
             std::shared_ptr<ProxyAuthenticationHTTPTrafficFilter> httpTrafficFilter = std::make_shared<ProxyAuthenticationHTTPTrafficFilter>();
             testling->setHTTPTrafficFilter(httpTrafficFilter);
 
-            connect(testling, HostAddressPort(HostAddress("2.2.2.2"), 2345));
+            connect(testling, HostAddressPort(HostAddress::fromString("2.2.2.2").get(), 2345));
 
             // First HTTP CONNECT request assumes the proxy will work.
             CPPUNIT_ASSERT_EQUAL(createByteArray("CONNECT 2.2.2.2:2345 HTTP/1.1\r\n"
diff --git a/Swiften/Network/UnitTest/HostAddressTest.cpp b/Swiften/Network/UnitTest/HostAddressTest.cpp
index aceb9be..226346b 100644
--- a/Swiften/Network/UnitTest/HostAddressTest.cpp
+++ b/Swiften/Network/UnitTest/HostAddressTest.cpp
@@ -25,10 +25,10 @@ class HostAddressTest : public CppUnit::TestFixture {
 
     public:
         void testConstructor() {
-            HostAddress testling("192.168.1.254");
+            auto testling = HostAddress::fromString("192.168.1.254");
 
-            CPPUNIT_ASSERT_EQUAL(std::string("192.168.1.254"), testling.toString());
-            CPPUNIT_ASSERT(testling.isValid());
+            CPPUNIT_ASSERT_EQUAL(std::string("192.168.1.254"), testling->toString());
+            CPPUNIT_ASSERT(testling->isValid());
         }
 
         void testConstructor_Invalid() {
@@ -38,9 +38,9 @@ class HostAddressTest : public CppUnit::TestFixture {
         }
 
         void testConstructor_InvalidString() {
-            HostAddress testling("invalid");
+            auto testling = HostAddress::fromString("invalid");
 
-            CPPUNIT_ASSERT(!testling.isValid());
+            CPPUNIT_ASSERT(!testling);
         }
 
         void testToString() {
diff --git a/Swiften/Network/WindowsProxyProvider.cpp b/Swiften/Network/WindowsProxyProvider.cpp
index 75e087a..78bd72f 100644
--- a/Swiften/Network/WindowsProxyProvider.cpp
+++ b/Swiften/Network/WindowsProxyProvider.cpp
@@ -22,7 +22,8 @@
 
 #include <Swiften/Base/ByteArray.h>
 #include <Swiften/Base/Log.h>
-#include <Swiften/Base/foreach.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/HostAddressPort.h>
 
 namespace Swift {
 
@@ -47,7 +48,7 @@ WindowsProxyProvider::WindowsProxyProvider()
         if(result == ERROR_SUCCESS) {
             std::vector<std::string> proxies = String::split(byteArrayToString(dataBuffer), ';');
             std::pair<std::string, std::string> protocolAndProxy;
-            foreach(std::string proxy, proxies) {
+            for(auto&& proxy : proxies) {
                 if(proxy.find('=') != std::string::npos) {
                     protocolAndProxy = String::getSplittedAtFirst(proxy, '=');
                     SWIFT_LOG(debug) << "Found proxy: " << protocolAndProxy.first << " => " << protocolAndProxy.second << std::endl;
@@ -81,10 +82,10 @@ HostAddressPort WindowsProxyProvider::getAsHostAddressPort(std::string proxy) {
         // .c_str() is needed as tmp.second can include a \0 char which will end in an exception of the lexical cast.
         // with .c_str() the \0 will not be part of the string which is to be casted
         port = boost::lexical_cast<int> (tmp.second.c_str());
-        ret = HostAddressPort(HostAddress(tmp.first), port);
+        ret = HostAddressPort(HostAddress::fromString(tmp.first).get(), port);
     }
     catch(...) {
-            SWIFT_LOG(error) << "Exception occured while parsing windows proxy \"getHostAddressPort\"." << std::endl;
+        SWIFT_LOG(error) << "Exception occured while parsing windows proxy \"getHostAddressPort\"." << std::endl;
     }
 
     return ret;
@@ -99,17 +100,20 @@ bool WindowsProxyProvider::proxyEnabled(HKEY hKey) const {
     DWORD data = 0;
     ByteArray dataBuffer;
 
-    if(hKey == INVALID_HANDLE_VALUE)
+    if(hKey == INVALID_HANDLE_VALUE) {
         return ret;
+    }
 
     result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, NULL, &dataSize);
-    if(result != ERROR_SUCCESS)
+    if(result != ERROR_SUCCESS) {
         return ret;
+    }
 
     dataBuffer.resize(dataSize);
     result = RegQueryValueEx(hKey, "ProxyEnable", NULL, &dataType, reinterpret_cast<BYTE*>(vecptr(dataBuffer)), &dataSize);
-    if(result != ERROR_SUCCESS)
+    if(result != ERROR_SUCCESS) {
         return ret;
+    }
 
     for(size_t t = 0; t < dataBuffer.size(); t++) {
         data += static_cast<int> (dataBuffer[t]) * pow(256, static_cast<double>(t));
diff --git a/Swiften/Network/WindowsProxyProvider.h b/Swiften/Network/WindowsProxyProvider.h
index ded5049..0ca897d 100644
--- a/Swiften/Network/WindowsProxyProvider.h
+++ b/Swiften/Network/WindowsProxyProvider.h
@@ -4,9 +4,16 @@
  * See Documentation/Licenses/BSD-simplified.txt for more information.
  */
 
+/*
+ * Copyright (c) 2016 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
 #pragma once
 
 #include <Swiften/Base/API.h>
+#include <Swiften/Network/HostAddressPort.h>
 #include <Swiften/Network/ProxyProvider.h>
 
 namespace Swift {
diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
index 859dcec..e639e20 100644
--- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
@@ -44,7 +44,7 @@ namespace Swift {
                 try {
                     port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1"));
                 } catch(boost::bad_lexical_cast &) { }
-                candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port);
+                candidate.hostPort = HostAddressPort(HostAddress::fromString(attributes.getAttributeValue("host").get_value_or("")).get_value_or(HostAddress()), port);
                 candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or(""));
                 int priority = -1;
                 try {
@@ -70,8 +70,6 @@ namespace Swift {
 
     void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
         --level;
-
-
     }
 
     void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) {
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
index 3bf79a5..c502c8a 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
@@ -5,7 +5,7 @@
  */
 
 /*
- * Copyright (c) 2015 Isode Limited.
+ * Copyright (c) 2015-2016 Isode Limited.
  * All rights reserved.
  * See the COPYING file for more information.
  */
@@ -520,14 +520,14 @@ class JingleParserTest : public CppUnit::TestFixture {
             candidate = s5bPayload->getCandidates()[0];
             CPPUNIT_ASSERT_EQUAL(std::string("hft54dqy"), candidate.cid);
             CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
-            CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.168.4.1"), 5086) == candidate.hostPort);
+            CPPUNIT_ASSERT(HostAddressPort(HostAddress::fromString("192.168.4.1").get(), 5086) == candidate.hostPort);
             CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
             CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
 
             candidate = s5bPayload->getCandidates()[1];
             CPPUNIT_ASSERT_EQUAL(std::string("hutr46fe"), candidate.cid);
             CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
-            CPPUNIT_ASSERT(HostAddressPort(HostAddress("24.24.24.1"), 5087) == candidate.hostPort);
+            CPPUNIT_ASSERT(HostAddressPort(HostAddress::fromString("24.24.24.1").get(), 5087) == candidate.hostPort);
             CPPUNIT_ASSERT_EQUAL(8258636, candidate.priority);
             CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
         }
@@ -594,21 +594,21 @@ class JingleParserTest : public CppUnit::TestFixture {
             candidate = s5bPayload->getCandidates()[0];
             CPPUNIT_ASSERT_EQUAL(std::string("ht567dq"), candidate.cid);
             CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
-            CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.169.1.10"), 6539) == candidate.hostPort);
+            CPPUNIT_ASSERT(HostAddressPort(HostAddress::fromString("192.169.1.10").get(), 6539) == candidate.hostPort);
             CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
             CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
 
             candidate = s5bPayload->getCandidates()[1];
             CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), candidate.cid);
             CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
-            CPPUNIT_ASSERT(HostAddressPort(HostAddress("134.102.201.180"), 16453) == candidate.hostPort);
+            CPPUNIT_ASSERT(HostAddressPort(HostAddress::fromString("134.102.201.180").get(), 16453) == candidate.hostPort);
             CPPUNIT_ASSERT_EQUAL(7929856, candidate.priority);
             CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::AssistedType, candidate.type);
 
             candidate = s5bPayload->getCandidates()[2];
             CPPUNIT_ASSERT_EQUAL(std::string("grt654q2"), candidate.cid);
             CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
-            CPPUNIT_ASSERT(HostAddressPort(HostAddress("2001:638:708:30c9:219:d1ff:fea4:a17d"), 6539) == candidate.hostPort);
+            CPPUNIT_ASSERT(HostAddressPort(HostAddress::fromString("2001:638:708:30c9:219:d1ff:fea4:a17d").get(), 6539) == candidate.hostPort);
             CPPUNIT_ASSERT_EQUAL(8257606, candidate.priority);
             CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
         }
diff --git a/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
index 11b0eb5..6982c0c 100644
--- a/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionServerTest.cpp
@@ -76,13 +76,13 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
         }
 
         void testIPv4Server() {
-            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("127.0.0.1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("127.0.0.1").get(), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
             testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
             testling->start();
 
             BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("127.0.0.1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -95,13 +95,13 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
         }
 
         void testIPv6Server() {
-            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::1"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::1").get(), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
             testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
             testling->start();
 
             BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("::1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -114,14 +114,14 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
         }
 
         void testIPv4IPv6DualStackServer() {
-            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::").get(), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
             testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
             testling->start();
 
             // Test IPv4.
             BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("127.0.0.1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -136,7 +136,7 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
             // Test IPv6.
             clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("::1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -149,14 +149,14 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
         }
 
         void testIPv6DualStackServerPeerAddress() {
-            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress("::"), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
+            BoostConnectionServer::ref testling = BoostConnectionServer::create(HostAddress::fromString("::").get(), 9999, boostIOServiceThread_->getIOService(), eventLoop_);
             testling->onNewConnection.connect(boost::bind(&BoostConnectionServerTest::handleNewConnection, this, _1));
             testling->start();
 
             // Test IPv4.
             BoostConnection::ref clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("127.0.0.1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("127.0.0.1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -165,7 +165,7 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
 
             CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
             // The IPv4 localhost mapped to a IPv6 address is expected here.
-            CPPUNIT_ASSERT(HostAddress("::ffff:127.0.0.1") == remoteAddress_.get().getAddress());
+            CPPUNIT_ASSERT(HostAddress::fromString("::ffff:127.0.0.1").get() == remoteAddress_.get().getAddress());
 
             receivedNewConnection_ = false;
             connectFinished_ = false;
@@ -174,7 +174,7 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
             // Test IPv6.
             clientTestling = BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_);
             clientTestling->onConnectFinished.connect(boost::bind(&BoostConnectionServerTest::handleConnectFinished, this, _1));
-            clientTestling->connect(HostAddressPort(HostAddress("::1"), 9999));
+            clientTestling->connect(HostAddressPort(HostAddress::fromString("::1").get(), 9999));
 
             while (!connectFinished_) {
                 Swift::sleep(10);
@@ -183,7 +183,7 @@ class BoostConnectionServerTest : public CppUnit::TestFixture {
 
             CPPUNIT_ASSERT_EQUAL(true, receivedNewConnection_);
             // The IPv6 local host is expected here.
-            CPPUNIT_ASSERT(HostAddress("::1") == remoteAddress_.get().getAddress());
+            CPPUNIT_ASSERT(HostAddress::fromString("::1").get() == remoteAddress_.get().getAddress());
 
             testling->stop();
         }
diff --git a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
index 12c4a77..e0890bf 100755
--- a/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
+++ b/Swiften/QA/NetworkTest/BoostConnectionTest.cpp
@@ -53,14 +53,18 @@ class BoostConnectionTest : public CppUnit::TestFixture {
         void testDestructor() {
             {
                 BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
-                testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+                auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+                CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+                testling->connect(HostAddressPort(hostAddress.get(), 5222));
             }
         }
 
         void testDestructor_PendingEvents() {
             {
                 BoostConnection::ref testling(BoostConnection::create(boostIOServiceThread_->getIOService(), eventLoop_));
-                testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+                auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+                CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+                testling->connect(HostAddressPort(hostAddress.get(), 5222));
                 while (!eventLoop_->hasEvents()) {
                     Swift::sleep(10);
                 }
@@ -75,7 +79,9 @@ class BoostConnectionTest : public CppUnit::TestFixture {
             testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
             testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
             testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
-            testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+            auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+            CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+            testling->connect(HostAddressPort(hostAddress.get(), 5222));
 
             boost::posix_time::ptime start = second_clock::local_time();
             while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60)))  {
@@ -93,7 +99,9 @@ class BoostConnectionTest : public CppUnit::TestFixture {
             testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::doWrite, this, testling.get()));
             testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
             testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
-            testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV6")), 5222));
+            auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV6"));
+            CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+            testling->connect(HostAddressPort(hostAddress.get(), 5222));
 
             boost::posix_time::ptime start = second_clock::local_time();
             while (receivedData_.empty() && ((second_clock::local_time() - start) < seconds(60)))  {
@@ -110,7 +118,10 @@ class BoostConnectionTest : public CppUnit::TestFixture {
             testling->onConnectFinished.connect(boost::bind(&BoostConnectionTest::handleConnectFinished, this));
             testling->onDataRead.connect(boost::bind(&BoostConnectionTest::handleDataRead, this, _1));
             testling->onDisconnected.connect(boost::bind(&BoostConnectionTest::handleDisconnected, this));
-            testling->connect(HostAddressPort(HostAddress(getenv("SWIFT_NETWORK_TEST_IPV4")), 5222));
+
+            auto hostAddress = HostAddress::fromString(getenv("SWIFT_NETWORK_TEST_IPV4"));
+            CPPUNIT_ASSERT_EQUAL(true, hostAddress.is_initialized());
+            testling->connect(HostAddressPort(hostAddress.get(), 5222));
             while (!connectFinished_) {
                 boostIOService_->run_one();
                 eventLoop_->processEvents();
diff --git a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
index d45d118..95ebb6d 100644
--- a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
+++ b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp
@@ -142,7 +142,7 @@ class DomainNameResolverTest : public CppUnit::TestFixture {
             waitForResults();
 
             CPPUNIT_ASSERT(!addressQueryError);
-            CPPUNIT_ASSERT(std::find(addressQueryResult.begin(), addressQueryResult.end(), HostAddress("127.0.0.1")) != addressQueryResult.end());
+            CPPUNIT_ASSERT(std::find(addressQueryResult.begin(), addressQueryResult.end(), HostAddress::fromString("127.0.0.1").get()) != addressQueryResult.end());
         }
 
         void testResolveAddress_Parallel() {
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
index 00d79b3..c259cce 100644
--- a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
@@ -379,7 +379,7 @@ class JingleSerializersTest : public CppUnit::TestFixture {
 
             JingleS5BTransportPayload::Candidate candidate1;
             candidate1.cid = "hft54dqy";
-            candidate1.hostPort = HostAddressPort(HostAddress("192.168.4.1"), 5086);
+            candidate1.hostPort = HostAddressPort(HostAddress::fromString("192.168.4.1").get(), 5086);
             candidate1.jid = JID("romeo@montague.lit/orchard");
             candidate1.priority = 8257636;
             candidate1.type = JingleS5BTransportPayload::Candidate::DirectType;
@@ -387,7 +387,7 @@ class JingleSerializersTest : public CppUnit::TestFixture {
 
             JingleS5BTransportPayload::Candidate candidate2;
             candidate2.cid = "hutr46fe";
-            candidate2.hostPort = HostAddressPort(HostAddress("24.24.24.1"), 5087);
+            candidate2.hostPort = HostAddressPort(HostAddress::fromString("24.24.24.1").get(), 5087);
             candidate2.jid = JID("romeo@montague.lit/orchard");
             candidate2.priority = 8258636;
             candidate2.type = JingleS5BTransportPayload::Candidate::DirectType;
-- 
cgit v0.10.2-6-g49f6