【问题标题】:How to parse network hostname + port in qt?如何在qt中解析网络主机名+端口?
【发布时间】:2014-05-21 20:42:59
【问题描述】:

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

example.org:1234

分成单独的主机名和端口 QStrings。

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

提前致谢!

【问题讨论】:

  • 您阅读过QUrl 文档吗? QUrl::host(), QUrl::port().
  • Thaks,还有一个问题:我如何在没有前置方案的情况下使用 QUrl(i.i.httpftp)等等?
  • @LocalToast:答案是否解决了问题?

标签: c++ qt networking qtcore qurl


【解决方案1】:

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

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

关于您避免在每个网址中使用方案的评论,you could use this

url.setScheme("ftp");

url.setScheme("http");

【讨论】:

    【解决方案2】:

    是的,你应该使用QUrl::fromUserInput函数来解析字符串,然后使用QUrl对象的hostport方法来得到你想要的QStrings。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多