refs #452 adjusted network utilities

* formatting
* new connect / URL methods
This commit is contained in:
Klaus Basan
2015-09-23 15:00:43 +02:00
committed by Mathew Sutcliffe
parent b5477c7c94
commit 567cead20d
2 changed files with 86 additions and 23 deletions

View File

@@ -9,6 +9,7 @@
#include <QCoreApplication>
#include <QHostAddress>
#include <QAbstractSocket>
#include <QUrl>
namespace BlackMisc
{
@@ -48,7 +49,7 @@ namespace BlackMisc
}
/*
* my IP
* My IP
*/
QStringList CNetworkUtils::getKnownIpAddresses()
{
@@ -103,6 +104,44 @@ namespace BlackMisc
return CNetworkUtils::canConnect(server.getAddress(), server.getPort(), message, timeoutMs);
}
/*
* Can connect url?
*/
bool CNetworkUtils::canConnect(const QString &url, QString &message, int timeoutMs)
{
if (url.isEmpty())
{
message = QObject::tr("Missing URL", "BlackMisc");
return false;
}
return canConnect(QUrl(url), message, timeoutMs);
}
/*
* Can connect url?
*/
bool CNetworkUtils::canConnect(const QUrl &url, QString &message, int timeoutMs)
{
if (!url.isValid())
{
message = QObject::tr("Invalid URL: %1", "BlackMisc").arg(url.toString());
return false;
}
if (url.isRelative())
{
message = QObject::tr("Relative URL cannot be tested: %1", "BlackMisc").arg(url.toString());
return false;
}
QString scheme(url.scheme().toLower());
int p = scheme.contains("https") ? 443 : 80;
p = url.port(80);
QString host(url.host());
return canConnect(host, p, message, timeoutMs);
}
/*
* Valid IPv4 address
*/
@@ -131,4 +170,23 @@ namespace BlackMisc
if (!success) return false;
return (p >= 1 && p <= 65535);
}
/*
* Build URL
*/
QString CNetworkUtils::buildUrl(const QString &protocol, const QString &server, const QString &baseUrl, const QString &serviceUrl)
{
Q_ASSERT_X(protocol.length() > 3, Q_FUNC_INFO, "worng protocol");
Q_ASSERT_X(!server.isEmpty(), Q_FUNC_INFO, "missing server");
Q_ASSERT_X(!serviceUrl.isEmpty(), Q_FUNC_INFO, "missing service URL");
QString url(server);
if (!baseUrl.isEmpty())
{
url.append("/").append(baseUrl);
}
url.append("/").append(serviceUrl);
url.replace("//", "/");
return protocol + "://" + url;
}
} // namespace