From 07f731df95903d428d167de3d55aa135a6d3b7fe Mon Sep 17 00:00:00 2001 From: levlam Date: Sun, 1 Jul 2018 02:10:17 +0300 Subject: [PATCH] Better init_host_port. GitOrigin-RevId: 04f6f90435cc7d33e18ab594658787044ec6c4f4 --- tdutils/td/utils/port/IPAddress.cpp | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/tdutils/td/utils/port/IPAddress.cpp b/tdutils/td/utils/port/IPAddress.cpp index ecc32c544..748966750 100644 --- a/tdutils/td/utils/port/IPAddress.cpp +++ b/tdutils/td/utils/port/IPAddress.cpp @@ -309,8 +309,9 @@ Status IPAddress::init_host_port(CSlice host, CSlice port) { addrinfo hints; addrinfo *info = nullptr; 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_protocol = IPPROTO_TCP; LOG(INFO) << "Try to init IP address of " << host << " with port " << port; auto err = getaddrinfo(host.c_str(), port.c_str(), &hints, &info); if (err != 0) { @@ -324,16 +325,21 @@ Status IPAddress::init_host_port(CSlice host, CSlice port) { freeaddrinfo(info); }; - // prefer ipv4 - addrinfo *best_info = info; - for (auto *ptr = info->ai_next; ptr != nullptr; ptr = ptr->ai_next) { - if (ptr->ai_socktype == AF_INET) { + addrinfo *best_info = nullptr; + for (auto *ptr = info; ptr != nullptr; ptr = ptr->ai_next) { + if (ptr->ai_family == AF_INET) { + // just use first IPv4 address best_info = ptr; 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(best_info->ai_addrlen)); }