-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Closed
Description
//
// Created by Kotarou on 2022/4/6.
//
#include <httplib.h>
std::unique_ptr<httplib::Client>
get_http_client(std::string_view url, int family = AF_UNSPEC, const char *nif_name = nullptr) {
auto client = std::make_unique<httplib::Client>(url.data());
// set outbound interface
if (nif_name != nullptr) {
client->set_interface(nif_name);
}
// set address family
client->set_address_family(family);
client->set_connection_timeout(5);
client->set_read_timeout(5, 1000);
client->set_follow_location(true);
client->set_default_headers({{"User-Agent", "Mozilla"}});
return client;
}
void print_response(const httplib::Result &result) {
if (result) {
std::cout << result->body << std::endl;
} else {
std::cerr << "Error: " << httplib::to_string(result.error()) << std::endl;
}
}
int main(int argc, char *argv[]) {
std::cout << "AF_UNSPEC, no nif" << std::endl;
auto client = get_http_client("https://api.ip.sb:443");
auto response = client->Get("/ip");
print_response(response);
std::cout << "AF_UNSPEC, en0" << std::endl;
client = get_http_client("https://api.ip.sb:443", AF_UNSPEC, "en0");
response = client->Get("/ip");
print_response(response);
std::cout << "AF_INET, no nif" << std::endl;
client = get_http_client("https://api.ip.sb:443", AF_INET);
response = client->Get("/ip");
print_response(response);
std::cout << "AF_INET, en0" << std::endl;
client = get_http_client("https://api.ip.sb:443", AF_INET, "en0");
response = client->Get("/ip");
print_response(response);
std::cout << "AF_INET6, no nif" << std::endl;
client = get_http_client("https://api.ip.sb:443", AF_INET6);
response = client->Get("/ip");
print_response(response);
std::cout << "AF_INET6, en0" << std::endl;
client = get_http_client("https://api.ip.sb:443", AF_INET6, "en0");
response = client->Get("/ip");
print_response(response);
return 0;
}
Output:
AF_UNSPEC, no nif
2405:aacf:acdc:6dc:33:cda2:153e:745
AF_UNSPEC, en0
38.13.192.76
AF_INET, no nif
38.13.192.76
AF_INET, en0
38.13.192.76
AF_INET6, no nif
2405:aacf:acdc:6dc:33:cda2:153e:745
AF_INET6, en0
Error: BindIPAddress
not sure what cause this, but when set address family to AF_INET6 and also force to use en0 as outbound interface, library returned a bind ip error.