multicast.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package beacon
  7. import "net"
  8. type Multicast struct {
  9. conn *net.UDPConn
  10. addr *net.UDPAddr
  11. intf *net.Interface
  12. inbox chan []byte
  13. outbox chan recv
  14. }
  15. func NewMulticast(addr, ifname string) (*Multicast, error) {
  16. gaddr, err := net.ResolveUDPAddr("udp6", addr)
  17. if err != nil {
  18. return nil, err
  19. }
  20. intf, err := net.InterfaceByName(ifname)
  21. if err != nil {
  22. return nil, err
  23. }
  24. conn, err := net.ListenMulticastUDP("udp6", intf, gaddr)
  25. if err != nil {
  26. return nil, err
  27. }
  28. b := &Multicast{
  29. conn: conn,
  30. addr: gaddr,
  31. intf: intf,
  32. inbox: make(chan []byte),
  33. outbox: make(chan recv, 16),
  34. }
  35. go genericReader(b.conn, b.outbox)
  36. go b.writer()
  37. return b, nil
  38. }
  39. func (b *Multicast) Send(data []byte) {
  40. b.inbox <- data
  41. }
  42. func (b *Multicast) Recv() ([]byte, net.Addr) {
  43. recv := <-b.outbox
  44. return recv.data, recv.src
  45. }
  46. func (b *Multicast) writer() {
  47. addr := *b.addr
  48. addr.Zone = b.intf.Name
  49. for bs := range b.inbox {
  50. _, err := b.conn.WriteTo(bs, &addr)
  51. if err != nil && debug {
  52. l.Debugln(err, "on write to", addr)
  53. } else if debug {
  54. l.Debugf("sent %d bytes to %s", len(bs), addr.String())
  55. }
  56. }
  57. }