How to parse host from URL in C++ using Boost::URL
If you have an URL such as:
std::string myURL = "https://subdomain.example.com/api/test";
you can parse the hostname from it using Boost::URL (you need at least Boost 1.81.0, previous versions of boost don’t have Boost.URL) using
boost::urls::url_view url(myURL);
std::string host = url.host();
std::cout << host << std::endl; // Prints "subdomain.example.com"
Full example:
#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"
}
Compile using
g++ -o urlhost urlhost.cpp -lboost_url