Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
AddressPool.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
20
21#pragma once
22
24
25#include <map>
26
27#ifdef _WIN32
28#pragma warning(disable : 4251)
29#endif
30
31namespace sese::net {
32
34template<class ADDRESS>
35class AddressPool final {
36public:
41 static std::shared_ptr<ADDRESS> lookup(const std::string &domain) noexcept;
42
43private:
44 AddressPool() = default;
45
47
48 std::map<std::string, std::shared_ptr<ADDRESS>> addressMap;
49};
50
51template<class ADDRESS>
53
56} // namespace sese::net
57
58
59template<class ADDRESS>
60std::shared_ptr<ADDRESS> sese::net::AddressPool<ADDRESS>::lookup(const std::string &domain) noexcept {
61 auto iterator = pool.addressMap.find(domain);
62 auto inet = std::is_same<ADDRESS, sese::net::IPv4Address>::value ? AF_INET : AF_INET6;
63 if (iterator == pool.addressMap.end()) {
64 auto address = ADDRESS::lookUpAny(domain, inet, IPPROTO_IP);
65 if (nullptr == address) {
66 // 未命中缓存且查找失败
67 return nullptr;
68 } else {
69 auto ip = dynamicPointerCast<ADDRESS>(address);
70 pool.addressMap[domain] = ip;
71 return ip;
72 }
73 } else {
74 return iterator->second;
75 }
76}