MDNSService.cpp 1.5 KB

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