Seastar
High performance C++ framework for concurrent servers
ipv4_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 #include <seastar/util/modules.hh>
28 
29 namespace seastar {
30 
31 namespace net {
32 
33 SEASTAR_MODULE_EXPORT_BEGIN
34 
35 struct ipv4_address {
36  ipv4_address() noexcept : ip(0) {}
37  explicit ipv4_address(uint32_t ip) noexcept : ip(ip) {}
38  // throws if addr is not a valid ipv4 address
39  explicit ipv4_address(const std::string& addr);
40  ipv4_address(ipv4_addr addr) noexcept {
41  ip = addr.ip;
42  }
43 
45 
46  template <typename Adjuster>
47  auto adjust_endianness(Adjuster a) { return a(ip); }
48 
49  friend bool operator==(ipv4_address x, ipv4_address y) noexcept {
50  return x.ip == y.ip;
51  }
52  friend bool operator!=(ipv4_address x, ipv4_address y) noexcept {
53  return x.ip != y.ip;
54  }
55 
56  static ipv4_address read(const char* p) noexcept {
57  ipv4_address ia;
58  ia.ip = read_be<uint32_t>(p);
59  return ia;
60  }
61  static ipv4_address consume(const char*& p) noexcept {
62  auto ia = read(p);
63  p += 4;
64  return ia;
65  }
66  void write(char* p) const noexcept {
67  write_be<uint32_t>(p, ip);
68  }
69  void produce(char*& p) const noexcept {
70  produce_be<uint32_t>(p, ip);
71  }
72  static constexpr size_t size() {
73  return 4;
74  }
75 } __attribute__((packed));
76 
77 inline bool is_unspecified(ipv4_address addr) noexcept { return addr.ip == 0; }
78 
79 std::ostream& operator<<(std::ostream& os, const ipv4_address& a);
80 
81 SEASTAR_MODULE_EXPORT_END
82 
83 }
84 
85 }
86 
87 namespace std {
88 
89 SEASTAR_MODULE_EXPORT
90 template <>
91 struct hash<seastar::net::ipv4_address> {
92  size_t operator()(seastar::net::ipv4_address a) const { return a.ip; }
93 };
94 
95 }
Seastar API namespace.
Definition: abort_on_ebadf.hh:26
Definition: socket_defs.hh:113
Definition: ipv4_address.hh:35
Definition: unaligned.hh:58