Better init_host_port.

GitOrigin-RevId: 04f6f90435cc7d33e18ab594658787044ec6c4f4
This commit is contained in:
levlam 2018-07-01 02:10:17 +03:00
parent 06481d89dd
commit 07f731df95

View File

@ -309,8 +309,9 @@ Status IPAddress::init_host_port(CSlice host, CSlice port) {
addrinfo hints; addrinfo hints;
addrinfo *info = nullptr; addrinfo *info = nullptr;
std::memset(&hints, 0, sizeof(hints)); std::memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; // TODO AF_UNSPEC; hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
LOG(INFO) << "Try to init IP address of " << host << " with port " << port; LOG(INFO) << "Try to init IP address of " << host << " with port " << port;
auto err = getaddrinfo(host.c_str(), port.c_str(), &hints, &info); auto err = getaddrinfo(host.c_str(), port.c_str(), &hints, &info);
if (err != 0) { if (err != 0) {
@ -324,16 +325,21 @@ Status IPAddress::init_host_port(CSlice host, CSlice port) {
freeaddrinfo(info); freeaddrinfo(info);
}; };
// prefer ipv4 addrinfo *best_info = nullptr;
addrinfo *best_info = info; for (auto *ptr = info; ptr != nullptr; ptr = ptr->ai_next) {
for (auto *ptr = info->ai_next; ptr != nullptr; ptr = ptr->ai_next) { if (ptr->ai_family == AF_INET) {
if (ptr->ai_socktype == AF_INET) { // just use first IPv4 address
best_info = ptr; best_info = ptr;
break; break;
} }
if (ptr->ai_family == AF_INET6 && best_info == nullptr) {
// or first IPv6 address if there is no IPv4
best_info = ptr;
}
}
if (best_info == nullptr) {
return Status::Error("Failed to find IPv4/IPv6 address");
} }
// just use first address
CHECK(best_info != nullptr);
return init_sockaddr(best_info->ai_addr, narrow_cast<socklen_t>(best_info->ai_addrlen)); return init_sockaddr(best_info->ai_addr, narrow_cast<socklen_t>(best_info->ai_addrlen));
} }