Seastar
High performance C++ framework for concurrent servers
ipv6_address.hh
1 /*
2  * This file is open source software, licensed to you under the terms
3  * of the Apache License, Version 2.0 (the "License"). See the NOTICE file
4  * distributed with this work for additional information regarding copyright
5  * ownership. You may not use this file except in compliance with the License.
6  *
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing,
12  * software distributed under the License is distributed on an
13  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14  * KIND, either express or implied. See the License for the
15  * specific language governing permissions and limitations
16  * under the License.
17  */
18 /*
19  * Copyright (C) 2022 ScyllaDB
20  *
21  */
22 
23 #pragma once
24 
25 #include <seastar/net/socket_defs.hh>
26 #include <seastar/core/byteorder.hh>
27 
28 #include <array>
29 
30 namespace seastar {
31 
32 namespace net {
33 
34 struct ipv6_address {
35  using ipv6_bytes = std::array<uint8_t, 16>;
36 
37  static_assert(alignof(ipv6_bytes) == 1, "ipv6_bytes should be byte-aligned");
38  static_assert(sizeof(ipv6_bytes) == 16, "ipv6_bytes should be 16 bytes");
39 
40  ipv6_address() noexcept;
41  explicit ipv6_address(const ::in6_addr&) noexcept;
42  explicit ipv6_address(const ipv6_bytes&) noexcept;
43  // throws if addr is not a valid ipv6 address
44  explicit ipv6_address(const std::string&);
45  ipv6_address(const ipv6_addr& addr) noexcept;
46 
47  // No need to use packed - we only store
48  // as byte array. If we want to read as
49  // uints or whatnot, we must copy
50  ipv6_bytes ip;
51 
52  template <typename Adjuster>
53  auto adjust_endianness(Adjuster a) { return a(ip); }
54 
55  bool operator==(const ipv6_address& y) const noexcept {
56  return bytes() == y.bytes();
57  }
58  bool operator!=(const ipv6_address& y) const noexcept {
59  return !(*this == y);
60  }
61 
62  const ipv6_bytes& bytes() const noexcept {
63  return ip;
64  }
65 
66  bool is_unspecified() const noexcept;
67 
68  static ipv6_address read(const char*) noexcept;
69  static ipv6_address consume(const char*& p) noexcept;
70  void write(char* p) const noexcept;
71  void produce(char*& p) const noexcept;
72  static constexpr size_t size() {
73  return sizeof(ipv6_bytes);
74  }
75 } __attribute__((packed));
76 
77 std::ostream& operator<<(std::ostream&, const ipv6_address&);
78 
79 }
80 
81 }
82 
83 namespace std {
84 
85 template <>
86 struct hash<seastar::net::ipv6_address> {
87  size_t operator()(const seastar::net::ipv6_address&) const;
88 };
89 
90 }
Seastar API namespace.
Definition: abort_on_ebadf.hh:26
Definition: socket_defs.hh:136
Definition: ipv6_address.hh:34
Definition: unaligned.hh:58