socket: Format IPv4-mapped IPv6 addresses as regular IPv4 address (#4382)

This commit is contained in:
Oxan van Leeuwen 2023-02-09 06:17:45 +01:00 committed by GitHub
parent 4d192c7387
commit 499cb615f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -18,16 +18,18 @@ std::string format_sockaddr(const struct sockaddr_storage &storage) {
if (storage.ss_family == AF_INET) { if (storage.ss_family == AF_INET) {
const struct sockaddr_in *addr = reinterpret_cast<const struct sockaddr_in *>(&storage); const struct sockaddr_in *addr = reinterpret_cast<const struct sockaddr_in *>(&storage);
char buf[INET_ADDRSTRLEN]; char buf[INET_ADDRSTRLEN];
const char *ret = inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)); if (inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) != nullptr)
if (ret == nullptr)
return {};
return std::string{buf}; return std::string{buf};
} else if (storage.ss_family == AF_INET6) { } else if (storage.ss_family == AF_INET6) {
const struct sockaddr_in6 *addr = reinterpret_cast<const struct sockaddr_in6 *>(&storage); const struct sockaddr_in6 *addr = reinterpret_cast<const struct sockaddr_in6 *>(&storage);
char buf[INET6_ADDRSTRLEN]; char buf[INET6_ADDRSTRLEN];
const char *ret = inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)); // Format IPv4-mapped IPv6 addresses as regular IPv4 addresses
if (ret == nullptr) if (addr->sin6_addr.un.u32_addr[0] == 0 && addr->sin6_addr.un.u32_addr[1] == 0 &&
return {}; addr->sin6_addr.un.u32_addr[2] == htonl(0xFFFF) &&
inet_ntop(AF_INET, &addr->sin6_addr.un.u32_addr[3], buf, sizeof(buf)) != nullptr) {
return std::string{buf};
}
if (inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)) != nullptr)
return std::string{buf}; return std::string{buf};
} }
return {}; return {};