Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
AsioIPConvert.h
浏览该文件的文档.
1// Copyright 2024 libsese
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#pragma once
16
18#include <asio.hpp>
19
20// GCOVR_EXCL_START
21
23inline asio::ip::address convert(const sese::net::IPAddress::Ptr &addr) {
24 if (addr->getRawAddress()->sa_family == AF_INET) {
25 const auto ipv4 = reinterpret_cast<sockaddr_in *>(addr->getRawAddress());
26 return asio::ip::make_address_v4(htonl(ipv4->sin_addr.s_addr));
27 }
28 const auto ipv6 = reinterpret_cast<sockaddr_in6 *>(addr->getRawAddress());
29 const std::array<unsigned char, 16> bytes = {
30 ipv6->sin6_addr.s6_addr[0],
31 ipv6->sin6_addr.s6_addr[1],
32 ipv6->sin6_addr.s6_addr[2],
33 ipv6->sin6_addr.s6_addr[3],
34 ipv6->sin6_addr.s6_addr[4],
35 ipv6->sin6_addr.s6_addr[5],
36 ipv6->sin6_addr.s6_addr[6],
37 ipv6->sin6_addr.s6_addr[7],
38 ipv6->sin6_addr.s6_addr[8],
39 ipv6->sin6_addr.s6_addr[9],
40 ipv6->sin6_addr.s6_addr[10],
41 ipv6->sin6_addr.s6_addr[11],
42 ipv6->sin6_addr.s6_addr[12],
43 ipv6->sin6_addr.s6_addr[13],
44 ipv6->sin6_addr.s6_addr[14],
45 ipv6->sin6_addr.s6_addr[15]
46 };
47 return asio::ip::make_address_v6(bytes, ipv6->sin6_scope_id);
48}
49
50template<typename EndpointType>
51sese::net::IPAddress::Ptr convert(const EndpointType& endpoint) {
52 static_assert(
53 std::is_same_v<EndpointType, asio::ip::tcp::endpoint> || std::is_same_v<EndpointType, asio::ip::udp::endpoint>,
54 "EndpointType must be either asio::ip::tcp::endpoint or asio::ip::udp::endpoint"
55 );
56
57 if (endpoint.address().is_v4()) {
58 sockaddr_in sockaddr{};
59 sockaddr.sin_family = AF_INET;
60 sockaddr.sin_port = htons(endpoint.port());
61 sockaddr.sin_addr.s_addr = htonl(endpoint.address().to_v4().to_uint());
62 return std::make_shared<sese::net::IPv4Address>(sockaddr);
63 }
64 sockaddr_in6 sockaddr{};
65 sockaddr.sin6_family = AF_INET6;
66 sockaddr.sin6_port = htons(endpoint.port());
67 auto bytes = endpoint.address().to_v6().to_bytes();
68 memcpy(&sockaddr.sin6_addr, bytes.data(), bytes.size());
69 return std::make_shared<sese::net::IPv6Address>(sockaddr);
70}
71
72} // namespace sese::internal::net
73
74// GCOVR_EXCL_STOP