You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用boost-url获取URL二级域名?是否提供内置函数?

用Boost.URL提取二级域名的方法

Boost.URL 目前没有直接提取二级域名的内置函数,它提供的 host() 方法仅能返回完整的主机名(比如 google.com)。

你的自定义提取方法对于 google.com 这类简单的双段域名确实有效,但存在局限性——无法处理包含多级子域名或特殊顶级域(如 co.uk)的场景(比如处理 bbc.co.uk 会得到错误的 bbc.co,而非实际的二级域名 bbc)。

以下是修正并完善后的示例代码(补充了result的类型声明,避免编译错误):

#include <boost/url.hpp>
#include <boost/system/result.hpp>
#include <iostream>

std::string get_sec_level_domain(std::string domain)
{
    std::size_t pos = domain.find_last_of('.');
    if (pos != std::string::npos && pos > 0)
    {
        std::string sld = domain.substr(0, pos);
        return sld;
    }
    return "";
}

int main()
{
    std::string url_str = "https://google.com";

    boost::system::result<boost::urls::url_view> result = boost::urls::parse_uri(url_str);
    if (!result) {
        std::cerr << "URL解析失败: " << result.error() << std::endl;
        return 1;
    }
    boost::urls::url_view url = result.value();

    std::string protocol = url.scheme();
    std::string domain = std::string(url.host());

    std::cout << protocol << std::endl; // 输出 `https`
    std::cout << domain << std::endl;   // 输出 `google.com`
    std::cout << get_sec_level_domain(domain) << std::endl; // 输出 `google`

    return 0;
}

如果需要处理更复杂的域名场景,你需要结合**公共后缀列表(Public Suffix List, PSL)**来准确识别顶级域,再提取对应的二级域名,但这部分逻辑需要自行实现或借助第三方库,Boost.URL本身不提供PSL相关功能。

内容的提问来源于stack exchange,提问作者Hassan Zubair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 01:19:57