fake_mdns_responder.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2018 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_FAKE_MDNS_RESPONDER_H_
  11. #define RTC_BASE_FAKE_MDNS_RESPONDER_H_
  12. #include <map>
  13. #include <memory>
  14. #include <string>
  15. #include "rtc_base/async_invoker.h"
  16. #include "rtc_base/ip_address.h"
  17. #include "rtc_base/location.h"
  18. #include "rtc_base/mdns_responder_interface.h"
  19. #include "rtc_base/thread.h"
  20. namespace webrtc {
  21. class FakeMdnsResponder : public MdnsResponderInterface {
  22. public:
  23. explicit FakeMdnsResponder(rtc::Thread* thread) : thread_(thread) {}
  24. ~FakeMdnsResponder() = default;
  25. void CreateNameForAddress(const rtc::IPAddress& addr,
  26. NameCreatedCallback callback) override {
  27. std::string name;
  28. if (addr_name_map_.find(addr) != addr_name_map_.end()) {
  29. name = addr_name_map_[addr];
  30. } else {
  31. name = std::to_string(next_available_id_++) + ".local";
  32. addr_name_map_[addr] = name;
  33. }
  34. invoker_.AsyncInvoke<void>(
  35. RTC_FROM_HERE, thread_,
  36. [callback, addr, name]() { callback(addr, name); });
  37. }
  38. void RemoveNameForAddress(const rtc::IPAddress& addr,
  39. NameRemovedCallback callback) override {
  40. auto it = addr_name_map_.find(addr);
  41. if (it != addr_name_map_.end()) {
  42. addr_name_map_.erase(it);
  43. }
  44. bool result = it != addr_name_map_.end();
  45. invoker_.AsyncInvoke<void>(RTC_FROM_HERE, thread_,
  46. [callback, result]() { callback(result); });
  47. }
  48. rtc::IPAddress GetMappedAddressForName(const std::string& name) const {
  49. for (const auto& addr_name_pair : addr_name_map_) {
  50. if (addr_name_pair.second == name) {
  51. return addr_name_pair.first;
  52. }
  53. }
  54. return rtc::IPAddress();
  55. }
  56. private:
  57. uint32_t next_available_id_ = 0;
  58. std::map<rtc::IPAddress, std::string> addr_name_map_;
  59. rtc::Thread* thread_;
  60. rtc::AsyncInvoker invoker_;
  61. };
  62. } // namespace webrtc
  63. #endif // RTC_BASE_FAKE_MDNS_RESPONDER_H_