0

I am trying to display the Ip address of a Raspberry Pi in a QTextEdit box;

IPAddress = new QTextEdit("Current IP Address: \n", this);
QString tem = QString::number(system("hostname -I"));
IPAddress->append(tem);
IPAddress->setStyleSheet("QTextEdit{border: none;outline:none;border-image: none;}");
IPAddress->show();

The Problem is this displays the IP Address as 0.

How do I get this to display the actual IP address?

MShields
  • 31
  • 1
  • 7

3 Answers3

2

Using system() is ugly and, unless you're coding a throwaway project, you should consider using QNetworkInterface class to do this.

dschulz
  • 4,666
  • 1
  • 31
  • 31
1

That's not a "problem", because:

QString::number(system("hostname -I")); 

returns "0" (most likely because system("hostname -I") command result is 0), so the QTextEdit displays 0.

Note that when you run a process:

  • It returns an exit code (main function returned value) as integer. In mostly all cases 0 means it succeeded, anything else means it fails.
  • It displays some information to standard output (what's sent to std::cout).

So, when you call system("hostname -I")) it returns 0 if successfull and then you need to parse its standard output to find the IP address that was printed here.

You can catch the call's standard output by using QProcess or by redirecting it to a file and then reading the file (system("hostname -I > ip.txt")may work, to be tested)

Or, to get your IP address as text, the best is to use QNetworkInterface, check this post, then you can display it in your QTextEdit.

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151
  • I am going to note that that I am doing this on a Raspberry Pi and on the terminal this command does display the ipaddress, but i may be misunderstanding something – MShields Oct 30 '15 at 11:32
  • You're mixing program result and output. See my edited post. – jpo38 Oct 30 '15 at 11:36
  • I am attempting to use the QNetwork Interface as shown in that post, however getting fairly constant build errors declaring that QHostAddress is undefined, i.e undefined reference to 'QHostAddress::~QHostAddress()' – MShields Oct 30 '15 at 11:53
  • Got it working forgot to add QT += network to pro file – MShields Oct 30 '15 at 12:20
0

Try this code:

 for (QHostAddress address: QNetworkInterface::allAddresses())
    if (address.protocol() == QAbstractSocket::IPv4Protocol)
       IPAddress->append(address.toString());
Roman Ozhegov
  • 231
  • 3
  • 15