mdns.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. import (
  5. "github.com/google/uuid"
  6. "github.com/pion/logging"
  7. "github.com/pion/mdns"
  8. "github.com/pion/transport/v2"
  9. "golang.org/x/net/ipv4"
  10. )
  11. // MulticastDNSMode represents the different Multicast modes ICE can run in
  12. type MulticastDNSMode byte
  13. // MulticastDNSMode enum
  14. const (
  15. // MulticastDNSModeDisabled means remote mDNS candidates will be discarded, and local host candidates will use IPs
  16. MulticastDNSModeDisabled MulticastDNSMode = iota + 1
  17. // MulticastDNSModeQueryOnly means remote mDNS candidates will be accepted, and local host candidates will use IPs
  18. MulticastDNSModeQueryOnly
  19. // MulticastDNSModeQueryAndGather means remote mDNS candidates will be accepted, and local host candidates will use mDNS
  20. MulticastDNSModeQueryAndGather
  21. )
  22. func generateMulticastDNSName() (string, error) {
  23. // https://tools.ietf.org/id/draft-ietf-rtcweb-mdns-ice-candidates-02.html#gathering
  24. // The unique name MUST consist of a version 4 UUID as defined in [RFC4122], followed by “.local”.
  25. u, err := uuid.NewRandom()
  26. return u.String() + ".local", err
  27. }
  28. func createMulticastDNS(n transport.Net, mDNSMode MulticastDNSMode, mDNSName string, log logging.LeveledLogger) (*mdns.Conn, MulticastDNSMode, error) {
  29. if mDNSMode == MulticastDNSModeDisabled {
  30. return nil, mDNSMode, nil
  31. }
  32. addr, mdnsErr := n.ResolveUDPAddr("udp4", mdns.DefaultAddress)
  33. if mdnsErr != nil {
  34. return nil, mDNSMode, mdnsErr
  35. }
  36. l, mdnsErr := n.ListenUDP("udp4", addr)
  37. if mdnsErr != nil {
  38. // If ICE fails to start MulticastDNS server just warn the user and continue
  39. log.Errorf("Failed to enable mDNS, continuing in mDNS disabled mode: (%s)", mdnsErr)
  40. return nil, MulticastDNSModeDisabled, nil
  41. }
  42. switch mDNSMode {
  43. case MulticastDNSModeQueryOnly:
  44. conn, err := mdns.Server(ipv4.NewPacketConn(l), &mdns.Config{})
  45. return conn, mDNSMode, err
  46. case MulticastDNSModeQueryAndGather:
  47. conn, err := mdns.Server(ipv4.NewPacketConn(l), &mdns.Config{
  48. LocalNames: []string{mDNSName},
  49. })
  50. return conn, mDNSMode, err
  51. default:
  52. return nil, mDNSMode, nil
  53. }
  54. }