| 1 | // Copyright (C) Microsoft Corporation. All rights reserved. |
| 2 | |
| 3 | #include "Utils.h" |
| 4 | #include "RuntimeErrorWithSourceLocation.h" |
| 5 | #include <iomanip> |
| 6 | #include <sstream> |
| 7 | #include <string.h> |
| 8 | |
| 9 | std::ostream& utils::FormatBinary(std::ostream& out, const void* ptr, size_t bytes) |
| 10 | { |
| 11 | out << "(" << bytes << " bytes) {"; |
| 12 | out << BytesToHex(ptr, bytes, ","); |
| 13 | |
| 14 | return out << "}"; |
| 15 | } |
| 16 | |
| 17 | std::string utils::BytesToHex(const void* ptr, size_t bytes, const std::string& separator) |
| 18 | { |
| 19 | std::stringstream out; |
| 20 | for (size_t i = 0; i < bytes; i++) |
| 21 | { |
| 22 | if (i != 0) |
| 23 | { |
| 24 | out << separator; |
| 25 | } |
| 26 | |
| 27 | out << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(reinterpret_cast<const std::uint8_t*>(ptr)[i]); |
| 28 | } |
| 29 | |
| 30 | return out.str(); |
| 31 | } |
| 32 | |
| 33 | Address utils::ComputeBroadcastAddress(const Address& address) |
| 34 | { |
| 35 | if (address.Family() != AF_INET) |
| 36 | { |
| 37 | throw RuntimeErrorWithSourceLocation(std::format("Can't compute broadcast address for address family: {}", address.Family())); |
| 38 | } |
| 39 | |
| 40 | auto bytes = address.AsBytes<in_addr>(); |
| 41 | |
| 42 | // Set all the bits between the prefixLength and 32 to 1 |
| 43 | std::uint32_t suffix = (1 << (32 - address.PrefixLength())) - 1; |
| 44 | bytes.s_addr |= htonl(suffix); |
| 45 | |
| 46 | return Address::FromBytes(AF_INET, address.PrefixLength(), bytes); |
| 47 | } |