mdns_client.cc 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2013 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "net/dns/mdns_client.h"
  5. #include "net/base/address_family.h"
  6. #include "net/base/net_errors.h"
  7. #include "net/base/network_interfaces.h"
  8. #include "net/dns/mdns_client_impl.h"
  9. #include "net/dns/public/util.h"
  10. #include "net/log/net_log.h"
  11. #include "net/log/net_log_source.h"
  12. namespace net {
  13. namespace {
  14. int Bind(AddressFamily address_family,
  15. uint32_t interface_index,
  16. DatagramServerSocket* socket) {
  17. socket->AllowAddressSharingForMulticast();
  18. socket->SetMulticastInterface(interface_index);
  19. int rv = socket->Listen(dns_util::GetMdnsReceiveEndPoint(address_family));
  20. if (rv < OK)
  21. return rv;
  22. return socket->JoinGroup(
  23. dns_util::GetMdnsGroupEndPoint(address_family).address());
  24. }
  25. } // namespace
  26. const base::TimeDelta MDnsTransaction::kTransactionTimeout = base::Seconds(3);
  27. // static
  28. std::unique_ptr<MDnsSocketFactory> MDnsSocketFactory::CreateDefault() {
  29. return std::make_unique<MDnsSocketFactoryImpl>();
  30. }
  31. // static
  32. std::unique_ptr<MDnsClient> MDnsClient::CreateDefault() {
  33. return std::make_unique<MDnsClientImpl>();
  34. }
  35. InterfaceIndexFamilyList GetMDnsInterfacesToBind() {
  36. NetworkInterfaceList network_list;
  37. InterfaceIndexFamilyList interfaces;
  38. if (!GetNetworkList(&network_list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES))
  39. return interfaces;
  40. for (const auto& network_interface : network_list) {
  41. AddressFamily family = GetAddressFamily(network_interface.address);
  42. if (family == ADDRESS_FAMILY_IPV4 || family == ADDRESS_FAMILY_IPV6) {
  43. interfaces.push_back(
  44. std::make_pair(network_interface.interface_index, family));
  45. }
  46. }
  47. std::sort(interfaces.begin(), interfaces.end());
  48. // Interfaces could have multiple addresses. Filter out duplicate entries.
  49. interfaces.erase(std::unique(interfaces.begin(), interfaces.end()),
  50. interfaces.end());
  51. return interfaces;
  52. }
  53. std::unique_ptr<DatagramServerSocket> CreateAndBindMDnsSocket(
  54. AddressFamily address_family,
  55. uint32_t interface_index,
  56. NetLog* net_log) {
  57. auto socket = std::make_unique<UDPServerSocket>(net_log, NetLogSource());
  58. int rv = Bind(address_family, interface_index, socket.get());
  59. if (rv != OK) {
  60. socket.reset();
  61. VLOG(1) << "MDNS bind failed, address_family=" << address_family
  62. << ", error=" << rv;
  63. }
  64. return socket;
  65. }
  66. } // namespace net