Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse network hostname + port in qt?

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!

like image 486
LocalToast Avatar asked Dec 17 '25 11:12

LocalToast


2 Answers

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");
like image 129
lpapp Avatar answered Dec 19 '25 01:12

lpapp


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()) };
like image 22
Evan Avatar answered Dec 18 '25 23:12

Evan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!