From 5e3775ae4c5263a25e63868e8a3f16244e4dde02 Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Thu, 3 Sep 2009 10:33:34 +0200 Subject: FortuneServer/Client example: fix displayed IP fortune server: listen to the first non-local IPv4 address found, fortune client: display that address as default in the line edit. Reviewed-by: Prasanth Ullattil Reviewed-by: Aleksandar Sasha Babic --- examples/network/fortuneclient/client.cpp | 15 ++++++++++++++- examples/network/fortuneserver/server.cpp | 19 ++++++++++++------- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/examples/network/fortuneclient/client.cpp b/examples/network/fortuneclient/client.cpp index b850a57..7b2991a 100644 --- a/examples/network/fortuneclient/client.cpp +++ b/examples/network/fortuneclient/client.cpp @@ -56,7 +56,20 @@ Client::Client(QWidget *parent) hostLabel = new QLabel(tr("&Server name:")); portLabel = new QLabel(tr("S&erver port:")); - hostLineEdit = new QLineEdit("Localhost"); + // find out which IP to connect to + QString ipAddress; + QList ipAddressesList = QNetworkInterface::allAddresses(); + // use the first non-localhost IPv4 address + for (int i = 0; i < ipAddressesList.size(); ++i) { + if (ipAddressesList.at(i) != QHostAddress::LocalHost && + ipAddressesList.at(i).toIPv4Address()) + ipAddress = ipAddressesList.at(i).toString(); + } + // if we did not find one, use IPv4 localhost + if (ipAddress.isEmpty()) + ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); + + hostLineEdit = new QLineEdit(ipAddress); portLineEdit = new QLineEdit; portLineEdit->setValidator(new QIntValidator(1, 65535, this)); diff --git a/examples/network/fortuneserver/server.cpp b/examples/network/fortuneserver/server.cpp index 7564199..476ff283 100644 --- a/examples/network/fortuneserver/server.cpp +++ b/examples/network/fortuneserver/server.cpp @@ -63,15 +63,20 @@ Server::Server(QWidget *parent) return; } //! [0] - QList ipAddresseList = QNetworkInterface::allAddresses(); - QString ipAddresses; - for (int i = 0; i < ipAddresseList.size(); ++i) { - ipAddresses.append(ipAddresseList.at(i).toString()).append("\n"); + QString ipAddress; + QList ipAddressesList = QNetworkInterface::allAddresses(); + // use the first non-localhost IPv4 address + for (int i = 0; i < ipAddressesList.size(); ++i) { + if (ipAddressesList.at(i) != QHostAddress::LocalHost && + ipAddressesList.at(i).toIPv4Address()) + ipAddress = ipAddressesList.at(i).toString(); } - - statusLabel->setText(tr("The server is running on \n IP: \n%1 PORT: \n%2\n" + // if we did not find one, use IPv4 localhost + if (ipAddress.isEmpty()) + ipAddress = QHostAddress(QHostAddress::LocalHost).toString(); + statusLabel->setText(tr("The server is running on\nIP: \n%1 port:\n%2\n" "Run the Fortune Client example now.") - .arg(ipAddresses).arg(tcpServer->serverPort())); + .arg(ipAddress).arg(tcpServer->serverPort())); //! [1] //! [2] -- cgit v0.12