如何在qt中解析网络主机名+端口?

Loc*_*ast 3 c++ networking qt qurl qtcore

我目前正在 Qt 中编写一个网络应用程序,需要以以下形式分隔网络地址:

example.org:1234
Run Code Online (Sandbox Code Playgroud)

到单独的主机名和端口 QStrings 中。

是否有 Qt 函数可以轻松解析它并检查给定的输入是否正确?

提前致谢!

lpa*_*app 6

这很简单;您只需将QUrl类与constructorhost()port()方法一起使用,如下所示:

QUrl url("http://example.org:1234")
qDebug() << "Host:" << url.host();
qDebug() << "Port:" << url.port();
Run Code Online (Sandbox Code Playgroud)

至于您关于避免在每个网址中使用方案的评论,您可以使用以下内容

url.setScheme("ftp");
Run Code Online (Sandbox Code Playgroud)

或者

url.setScheme("http");
Run Code Online (Sandbox Code Playgroud)