Hugo Benichi | 2ac4d07 | 2019-05-28 14:51:23 +0900 | [diff] [blame] | 1 | // Copyright 2019 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include <stdint.h> |
| 6 | |
| 7 | #include <string> |
| 8 | |
Garrick Evans | 5486162 | 2019-07-19 09:05:09 +0900 | [diff] [blame^] | 9 | #include "arc/network/mac_address_generator.h" |
| 10 | |
Hugo Benichi | 2ac4d07 | 2019-05-28 14:51:23 +0900 | [diff] [blame] | 11 | #ifndef ARC_NETWORK_NET_UTIL_H_ |
| 12 | #define ARC_NETWORK_NET_UTIL_H_ |
| 13 | |
| 14 | namespace arc_networkd { |
| 15 | |
| 16 | // Reverses the byte order of the argument. |
| 17 | constexpr uint32_t Byteswap32(uint32_t x) { |
| 18 | return (x >> 24) | (x << 24) | ((x >> 8) & 0xff00) | ((x << 8) & 0xff0000); |
| 19 | } |
| 20 | |
| 21 | // Reverses the byte order of the argument. |
| 22 | constexpr uint16_t Byteswap16(uint16_t x) { |
| 23 | return (x >> 8) | (x << 8); |
| 24 | } |
| 25 | |
| 26 | // Constexpr version of ntohl(). |
| 27 | constexpr uint32_t Ntohl(uint32_t x) { |
| 28 | return Byteswap32(x); |
| 29 | } |
| 30 | |
| 31 | // Constexpr version of htonl(). |
| 32 | constexpr uint32_t Htonl(uint32_t x) { |
| 33 | return Byteswap32(x); |
| 34 | } |
| 35 | |
| 36 | // Constexpr version of ntohs(). |
| 37 | constexpr uint16_t Ntohs(uint16_t x) { |
| 38 | return Byteswap16(x); |
| 39 | } |
| 40 | |
| 41 | // Constexpr version of htons(). |
| 42 | constexpr uint16_t Htons(uint16_t x) { |
| 43 | return Byteswap16(x); |
| 44 | } |
| 45 | |
| 46 | // Returns the network-byte order int32 representation of the IPv4 address given |
| 47 | // byte per byte, most significant bytes first. |
| 48 | constexpr uint32_t Ipv4Addr(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { |
| 49 | return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0; |
| 50 | } |
| 51 | |
| 52 | // Returns the literal representation of the IPv4 address given in network byte |
| 53 | // order. |
| 54 | std::string IPv4AddressToString(uint32_t addr); |
| 55 | |
| 56 | // Returns the CIDR representation of an IPv4 address given in network byte |
| 57 | // order. |
| 58 | std::string IPv4AddressToCidrString(uint32_t addr, uint32_t prefix_length); |
| 59 | |
Garrick Evans | 5486162 | 2019-07-19 09:05:09 +0900 | [diff] [blame^] | 60 | // Returns a string representation of MAC address given. |
| 61 | std::string MacAddressToString(const MacAddress& addr); |
| 62 | |
Hugo Benichi | 2ac4d07 | 2019-05-28 14:51:23 +0900 | [diff] [blame] | 63 | } // namespace arc_networkd |
| 64 | |
| 65 | #endif // ARC_NETWORK_NET_UTIL_H_ |