blob: 42853ac18d8e01b8c563d34251c9c275401d894d [file] [log] [blame]
Hugo Benichi2ac4d072019-05-28 14:51:23 +09001// 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
9#ifndef ARC_NETWORK_NET_UTIL_H_
10#define ARC_NETWORK_NET_UTIL_H_
11
12namespace arc_networkd {
13
14// Reverses the byte order of the argument.
15constexpr uint32_t Byteswap32(uint32_t x) {
16 return (x >> 24) | (x << 24) | ((x >> 8) & 0xff00) | ((x << 8) & 0xff0000);
17}
18
19// Reverses the byte order of the argument.
20constexpr uint16_t Byteswap16(uint16_t x) {
21 return (x >> 8) | (x << 8);
22}
23
24// Constexpr version of ntohl().
25constexpr uint32_t Ntohl(uint32_t x) {
26 return Byteswap32(x);
27}
28
29// Constexpr version of htonl().
30constexpr uint32_t Htonl(uint32_t x) {
31 return Byteswap32(x);
32}
33
34// Constexpr version of ntohs().
35constexpr uint16_t Ntohs(uint16_t x) {
36 return Byteswap16(x);
37}
38
39// Constexpr version of htons().
40constexpr uint16_t Htons(uint16_t x) {
41 return Byteswap16(x);
42}
43
44// Returns the network-byte order int32 representation of the IPv4 address given
45// byte per byte, most significant bytes first.
46constexpr uint32_t Ipv4Addr(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) {
47 return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0;
48}
49
50// Returns the literal representation of the IPv4 address given in network byte
51// order.
52std::string IPv4AddressToString(uint32_t addr);
53
54// Returns the CIDR representation of an IPv4 address given in network byte
55// order.
56std::string IPv4AddressToCidrString(uint32_t addr, uint32_t prefix_length);
57
Hugo Benichi2ac4d072019-05-28 14:51:23 +090058} // namespace arc_networkd
59
60#endif // ARC_NETWORK_NET_UTIL_H_