Как разобрать хост из URL в C++ с использованием Boost::URL

Если у вас есть URL, такой как:

snippet.cpp
std::string myURL = "https://subdomain.example.com/api/test";

вы можете разобрать имя хоста из него с использованием Boost::URL (вам нужен как минимум Boost 1.81.0, предыдущие версии boost не имеют Boost.URL) с помощью

snippet2.cpp
boost::urls::url_view url(myURL);
std::string host = url.host();

std::cout << host << std::endl; // Prints "subdomain.example.com"

Полный пример:

urlhost.cpp
#include <string>
#include <iostream>

#include <boost/url.hpp>

int main() {
    std::string myURL = "https://subdomain.example.com/api/test";

    boost::urls::url_view url(myURL);
    std::string host = url.host();

    std::cout << host << std::endl; // Prints "subdomain.example.com"
}

Компиляция с помощью

build_urlhost.sh
g++ -o urlhost urlhost.cpp -lboost_url

Check out similar posts by category: Boost C/C++