MDNSService.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "MDNSService.h"
  2. #include <stddef.h> // for NULL
  3. #include <utility> // for pair
  4. #include "dns_sd.h" // for DNSServiceRef, DNSServiceRefDeallocate, DNS...
  5. #include "i386/endian.h" // for htons
  6. using namespace bell;
  7. class implMDNSService : public MDNSService {
  8. private:
  9. DNSServiceRef* service;
  10. public:
  11. implMDNSService(DNSServiceRef* service) : service(service) {}
  12. void unregisterService() { DNSServiceRefDeallocate(*service); }
  13. };
  14. /**
  15. * MacOS implementation of MDNSService.
  16. * @see https://developer.apple.com/documentation/dnssd/1804733-dnsserviceregister
  17. **/
  18. std::unique_ptr<MDNSService> MDNSService::registerService(
  19. const std::string& serviceName, const std::string& serviceType,
  20. const std::string& serviceProto, const std::string& serviceHost,
  21. int servicePort, const std::map<std::string, std::string> txtData) {
  22. DNSServiceRef* ref = new DNSServiceRef();
  23. TXTRecordRef txtRecord;
  24. TXTRecordCreate(&txtRecord, 0, NULL);
  25. for (auto& data : txtData) {
  26. TXTRecordSetValue(&txtRecord, data.first.c_str(), data.second.size(),
  27. data.second.c_str());
  28. }
  29. DNSServiceRegister(ref, /* sdRef */
  30. 0, /* flags */
  31. 0, /* interfaceIndex */
  32. serviceName.c_str(), /* name */
  33. (serviceType + "." + serviceProto)
  34. .c_str(), /* regType (_spotify-connect._tcp) */
  35. NULL, /* domain */
  36. NULL, /* host */
  37. htons(servicePort), /* port */
  38. TXTRecordGetLength(&txtRecord), /* txtLen */
  39. TXTRecordGetBytesPtr(&txtRecord), /* txtRecord */
  40. NULL, /* callBack */
  41. NULL /* context */
  42. );
  43. TXTRecordDeallocate(&txtRecord);
  44. return std::make_unique<implMDNSService>(ref);
  45. }