3

I am currently writing a network application in Qt and need to seperate network adresses in the form:

example.org:1234

into seperate hostname and port QStrings.

Is there a Qt function to easily parse this and check if the given input is correct?

Thanks in advance!

László Papp
  • 51,870
  • 39
  • 111
  • 135
LocalToast
  • 397
  • 1
  • 5
  • 13

2 Answers2

5

This is quite simple; you just use the QUrl class for this with the constructor, host() and port() methods as follows:

QUrl url("http://example.org:1234")
qDebug() << "Host:" << url.host();
qDebug() << "Port:" << url.port();

As for your comment for avoiding the scheme usage in each url, you could use this:

url.setScheme("ftp");

or

url.setScheme("http");
László Papp
  • 51,870
  • 39
  • 111
  • 135
1

Yes, you should use the QUrl::fromUserInput function to parse the string, and then the host and port methods of the QUrl object to get the QStrings that you want.

auto url{ QUrl::fromUserInput(address) };
auto host{ url.host() };
auto port{ QString::number(url.port()) };
Evan
  • 53
  • 10