示例#1
0
// NewServer is used to create a new mDNS server from a config
func NewServer(config *Config) (*Server, error) {
	// Create the listeners
	ipv4List, err := net.ListenMulticastUDP("udp4", config.Iface, ipv4Addr)
	if err != nil {
		log.Printf("[ERR] mdns: Failed to start IPv4 listener: %v", err)
	}
	ipv6List, err := net.ListenMulticastUDP("udp6", config.Iface, ipv6Addr)
	if err != nil {
		log.Printf("[ERR] mdns: Failed to start IPv6 listener: %v", err)
	}

	// Check if we have any listener
	if ipv4List == nil && ipv6List == nil {
		return nil, fmt.Errorf("No multicast listeners could be started")
	}

	s := &Server{
		config:     config,
		ipv4List:   ipv4List,
		ipv6List:   ipv6List,
		shutdownCh: make(chan struct{}),
	}
	go s.recv(s.ipv4List)
	go s.recv(s.ipv6List)
	return s, nil
}
示例#2
0
文件: mdns.go 项目: zserge/mdns
func NewMDNS(hostname string, services map[string]int) (MDNS, error) {
	rrs, err := localRR(hostname, services)
	if err != nil {
		return nil, err
	}

	connv4, err := net.ListenMulticastUDP("udp4", nil, ipv4mcastaddr)
	if err != nil {
		return nil, err
	}

	connv6, err := net.ListenMulticastUDP("udp6", nil, ipv6mcastaddr)
	if err != nil {
		connv6 = nil
	}

	m := &mdns{
		local:   rrs,
		connv4:  connv4,
		connv6:  connv6,
		pending: []*query{},
		queries: make(chan *query, 64),
		exit:    make(chan bool, 0),
	}

	qst := make(chan msg, 0)
	go m.loop(qst)
	go m.readloop(connv4, qst)
	go m.readloop(connv6, qst)

	return m, nil
}
示例#3
0
文件: server.go 项目: bmatsuo/mdns
// NewServer is used to create a new mDNS server from a config
func NewServer(config *Config) (*Server, error) {
	// Create the listeners
	ipv4List, _ := net.ListenMulticastUDP("udp4", config.Iface, ipv4Addr)
	ipv6List, _ := net.ListenMulticastUDP("udp6", config.Iface, ipv6Addr)

	// Check if we have any listener
	if ipv4List == nil && ipv6List == nil {
		return nil, fmt.Errorf("No multicast listeners could be started")
	}

	s := &Server{
		config:     config,
		ipv4List:   ipv4List,
		ipv6List:   ipv6List,
		shutdownCh: make(chan struct{}),
	}

	if ipv4List != nil {
		go s.recv(s.ipv4List)
	}

	if ipv6List != nil {
		go s.recv(s.ipv6List)
	}

	return s, nil
}
示例#4
0
文件: mdns.go 项目: davecheney/mdns
func openSocket(addr *net.UDPAddr) (*net.UDPConn, error) {
	switch addr.IP.To4() {
	case nil:
		return net.ListenMulticastUDP("udp6", nil, ipv6mcastaddr)
	default:
		return net.ListenMulticastUDP("udp4", nil, ipv4mcastaddr)
	}
	panic("unreachable")
}
示例#5
0
// Constructs server structure
func newServer(iface *net.Interface) (*server, error) {
	// Create wildcard connections (because :5353 can be already taken by other apps)
	ipv4conn, err := net.ListenMulticastUDP("udp4", iface, mdnsWildcardAddrIPv4)
	if err != nil {
		log.Printf("[ERR] bonjour: Failed to bind to udp4 port: %v", err)
	}
	ipv6conn, err := net.ListenMulticastUDP("udp6", iface, mdnsWildcardAddrIPv6)
	if ipv4conn == nil && ipv6conn == nil {
		return nil, fmt.Errorf("[ERR] bonjour: Failed to bind to any udp port!")
	}

	// Join multicast groups to receive announcements
	p1 := ipv4.NewPacketConn(ipv4conn)
	p2 := ipv6.NewPacketConn(ipv6conn)
	if iface != nil {
		errCount := 0
		if err := p1.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
			errCount++
		}
		if err := p2.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
			errCount++
		}
		if errCount == 2 {
			return nil, fmt.Errorf("Failed to join multicast group on both v4 and v6")
		}
	} else {
		ifaces, err := net.Interfaces()
		if err != nil {
			return nil, err
		}
		errCount1, errCount2 := 0, 0
		for _, iface := range ifaces {
			if err := p1.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
				errCount1++
			}
			if err := p2.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
				errCount2++
			}
		}
		if len(ifaces) == errCount1 && len(ifaces) == errCount2 {
			return nil, fmt.Errorf("Failed to join multicast group on all interfaces!")
		}
	}

	s := &server{
		ipv4conn:   ipv4conn,
		ipv6conn:   ipv6conn,
		shutdownCh: make(chan bool),
	}

	return s, nil
}
示例#6
0
func (conn *Connection) setupSockets() (err error) {
	// NOTE(bo): On the IP address used for send and receive connections.
	//
	// Go only sets SO_REUSEADDR and SO_REUSEPORT when using a Multicast
	// IP address[1][2][3]. Without dropping down to C, there isn't a way great around
	// this.
	//
	// Despite not being the 255.255.255.255 used in other LIFX libraries, In
	// practice, it seems to work for receiving messages. Sending messages is
	// still somewhat unverified.
	//
	// I may be confusing multicast and broadcast a bit here, but I don't know how else to
	// enable binding to the same interface and port multiple times...
	//
	// [1]: http://golang.org/src/pkg/net/sock_posix.go?h=setDefaultMulticastSockopts#L161
	// [2]: http://golang.org/src/pkg/net/sockopt_bsd.go (also ./sockopt_linux.go)
	// [3]: http://en.wikipedia.org/wiki/Multicast_address#Local_subnetwork
	ip := net.IPv4(224, 0, 0, 1)

	peer, err := net.ListenMulticastUDP("udp4", nil, &net.UDPAddr{
		IP:   ip,
		Port: peerPort,
	})
	if err != nil {
		return
	}

	broadcast, err := net.ListenMulticastUDP("udp4", nil, &net.UDPAddr{
		IP:   ip,
		Port: broadcastPort,
	})
	if err != nil {
		return
	}

	write, err := net.DialUDP("udp4", nil, &net.UDPAddr{
		IP:   ip,
		Port: broadcastPort,
	})
	if err != nil {
		return
	}

	conn.sockets.peer = peer
	conn.sockets.broadcast = broadcast
	conn.sockets.write = write

	return
}
示例#7
0
// Server which listens for incoming multicast requests on the specified interface. Upon receive of a
// request it sends the registry address to the asking client.
func registryLookupServiceOnInterface(address *net.TCPAddr, intf net.Interface, ch chan int) {
	response := LookupAddressResponse{*address}
	buffer := make([]byte, PACKET_SIZE)

	connection, err := net.ListenMulticastUDP(UDP_PROTOCOL, &intf, MULTICAT_ADDR)
	if err != nil {
		return
	}
	defer connection.Close()

	bytes, err := json.Marshal(response)
	if err != nil {
		return
	}

	for {
		_, sender, err := connection.ReadFromUDP(buffer)
		if err != nil {
			return
		}
		_, err = connection.WriteToUDP(bytes, sender)
		if err != nil {
			return
		}
	}

	ch <- 0
}
示例#8
0
/*
	Joins a multicast group as a listener on the named interface
*/
func (this *Cmgr) Listen_mc(ifname string, addr string, data2usr chan *Sess_data) (sessid string, err error) {

	sessid = ""
	iface, err := net.InterfaceByName(ifname)
	if err != nil {
		return
	}

	sessid = fmt.Sprintf("m%d", this.mcount) // successful bind to port
	this.mcount++

	uaddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return
	}

	uconn, err := net.ListenMulticastUDP("udp", iface, uaddr)
	if err != nil {
		return
	}

	cp := new(connection)
	cp.conn = nil
	cp.uconn = uconn
	cp.data2usr = data2usr  // session data written to this channel
	cp.id = sessid          // user assigned session id
	this.clist[sessid] = cp // hash for write to session

	go this.conn_reader(cp) // start reader; will discard if data2usr is nil

	return sessid, err
}
示例#9
0
func main() {
	maddr, err := net.ResolveUDPAddr("udp", "239.0.0.1:1234")
	if err != nil {
		log.Fatalln("Failed to resolve UDP addr")
	}

	mconn, err := net.ListenMulticastUDP("udp", nil, maddr)
	if err != nil {
		log.Fatalln("Failed to listen at UDP addr")
	}

	wconn, err := net.DialUDP("udp", nil, maddr)
	if err != nil {
		log.Fatalln("Failed to blah")
	}

	buf := make([]byte, 96)
	for i := 0; i < 10; i++ {
		n, err := mconn.Read(buf)

		if err != nil {
			log.Fatalln("Failed to read from UDP conn")
		}

		log.Printf("Read %v bytes: %v\n", n, string(buf[:n]))

		n, err = wconn.Write(append([]byte("pong"), buf[:n]...))

		if err != nil {
			log.Fatalln("Failed to write to UDP conn", err)
		}
	}
}
示例#10
0
func Listen(service Service, addr, port string) {
	buffSize := service.BuffSize()

	ServerAddr, err := net.ResolveUDPAddr("udp", addr+":"+port)
	if err != nil {
		log.Println("ERROR: discovery.Listen ResolveUDPAddr: ", err)
		return
	}

	ServerConn, err := net.ListenMulticastUDP("udp", nil, ServerAddr)
	defer ServerConn.Close()
	ServerConn.SetReadBuffer(buffSize)
	if err != nil {
		log.Println("ERROR: discovery.Listen ListenUDP: ", err)
		return
	}
	service.SetPort(Port(ServerConn.LocalAddr()))

	for {
		buf := make([]byte, buffSize)
		n, addr, err := ServerConn.ReadFromUDP(buf)
		if err != nil {
			log.Println("ERROR: discovery.Listen ReadFromUDP: ", err)
			continue
		}
		buf = bytes.Trim(buf, "\x00")
		buf, err = crypto.Decrypt(service, buf)
		if err != nil {
			log.Println("ERROR: discovery.Listen Decrypt: ", err)
			continue
		}
		service.Handle(buf, n, addr)
	}
}
示例#11
0
func (a *Server) bind() (conn *net.UDPConn, err error) {
	if !a.NotMulticast && a.iface.Flags&net.FlagMulticast == net.FlagMulticast {
		gaddr, err := a.groupAddr()
		if err != nil {
			return nil, e.Forward(err)
		}
		conn, err = net.ListenMulticastUDP(a.Proto(), a.iface, gaddr)
		if err != nil {
			return nil, e.New(err)
		}
	} else {
		server, err := net.ResolveUDPAddr(a.Proto(), ":"+a.Port)
		if err != nil {
			return nil, e.New(err)
		}
		conn, err = net.ListenUDP(a.Proto(), server)
		if err != nil {
			return nil, e.New(err)
		}
	}
	a.ipver(conn.LocalAddr())
	_, a.Port, err = utilNet.SplitHostPort(conn.LocalAddr().String())
	if err != nil {
		return nil, e.Forward(err)
	}
	return
}
示例#12
0
// Bind starts listening on udp addr.
// if emitter is true, bind to :0 and write to c.addr
// else bind to c.addr and read from c.addr
func (c *Conn) Bind(emitter bool) error {
	var addr *net.UDPAddr
	var conn *net.UDPConn
	var err error

	if emitter {
		addr, err = net.ResolveUDPAddr("udp", ":0")
	} else {
		addr = c.addr
	}

	if err != nil {
		return err
	}

	if addr.IP != nil && addr.IP.IsMulticast() {
		conn, err = net.ListenMulticastUDP("udp", nil, addr)
	} else {
		conn, err = net.ListenUDP("udp", addr)
	}

	if err != nil {
		return err
	}

	c.socket = conn
	return nil
}
示例#13
0
文件: NetInput.go 项目: aktungmak/chq
func NewNetInput(address string, port int) (*NetInput, error) {
	var err error
	var conn *net.UDPConn

	n := &NetInput{}
	n.addr = net.UDPAddr{
		Port: port,
		IP:   net.ParseIP(address),
	}
	n.input = nil

	// the stream may be unicast or multicast, so choose appropriately
	if n.addr.IP.IsMulticast() {
		conn, err = net.ListenMulticastUDP("udp", nil, &n.addr)
	} else {
		conn, err = net.ListenUDP("udp", &n.addr)
	}
	if err != nil {
		conn.Close()
		return nil, err
	}
	n.conn = conn

	go n.process()
	return n, nil
}
示例#14
0
func main() {
	maddr, err := net.ResolveUDPAddr("udp", "239.255.43.99:1090")
	check(err)
	fmt.Printf("%#v\n", maddr)
	conn, err := net.ListenMulticastUDP("udp", nil, maddr)
	check(err)
	go func(conn *net.UDPConn) {
		for {
			buf := make([]byte, 12)
			now := time.Now()
			conn.SetDeadline(now.Add(time.Second * 5))
			n, addr, err := conn.ReadFromUDP(buf)
			fmt.Println("\ninput from udp:", buf, n, addr, err)
		}
	}(conn)

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Input: ")
		t, _, _ := reader.ReadLine()
		if len(t) == 0 {
			fmt.Println("Bye")
			os.Exit(0)
		}
		fmt.Println("Got input:", t)
		b := make([]byte, 12)
		copy(b, t)
		n, err := conn.WriteToUDP(b, maddr)
		check(err)
		fmt.Println("Sent to udp:", n, err)
	}

}
示例#15
0
文件: udp.go 项目: liamstask/go-rtps
func udpAddMcastRX(addr string) error {
	udpaddr, err := net.ResolveUDPAddr("udp", addr)
	if err != nil {
		return err
	}

	// have we already added this ctx?
	for _, c := range defaultUDPConfig.rxers {
		if c.addr == udpaddr {
			return nil
		}
	}

	// XXX: ability to specify interfaces
	// XXX: may need more sophisticated handling for multicast
	udpconn, err := net.ListenMulticastUDP("udp", nil, udpaddr)
	if err != nil {
		return err
	}

	println("adding mcast:", addr)

	rxer := udpCtx{udpconn, udpaddr}
	defaultUDPConfig.rxers = append(defaultUDPConfig.rxers, rxer)

	go rxer.rx()
	return nil
}
示例#16
0
func ListenTo(iface *net.Interface, addr *net.UDPAddr, burstChannel chan *Burst) error {
	conn, err := net.ListenMulticastUDP("udp", iface, addr)
	if err != nil {
		return err
	}

	body := func() {
		defer conn.Close()

		buf := make([]byte, 65536)

		for {
			count, err := conn.Read(buf)
			if err != nil {
				log.Fatalf("Bad read in ListenTo: %s", err.Error())
			}

			burst, used, err := DecodeBurst(buf[0:count])
			if err != nil {
				log.Printf("Bad decode in ListenTo: %s", err.Error())
			}
			_ = used

			burstChannel <- burst
		}
	}

	go body()

	return nil
}
示例#17
0
func receive(group *net.UDPAddr, ids chan multicastId) {
	socket, err := net.ListenMulticastUDP("udp4", nil, group)
	if err != nil {
		panic(err)
	}
	defer socket.Close()

	socketBufferSize := 4096
	for {
		buf := make([]byte, socketBufferSize)
		n, err := socket.Read(buf)
		if err != nil {
			log.Printf("Multicast Discovery: receive: %s (exiting)", err)
			return
		}
		if n >= socketBufferSize {
			panic(fmt.Sprintf("%d >= %d", n, socketBufferSize))
		}

		var id multicastId
		if err := json.Unmarshal(buf[:n], &id); err != nil {
			continue
		}
		ids <- id
	}
}
示例#18
0
func main() {
	port := "224.0.1.60:1888"
	laddr, err := net.ResolveUDPAddr("udp", ":0")
	check(err)
	mcaddr, err := net.ResolveUDPAddr("udp", port)
	check(err)
	conn, err := net.ListenMulticastUDP("udp", nil, mcaddr)
	check(err)
	lconn, err := net.ListenUDP("udp", laddr)
	check(err)
	reader := bufio.NewReader(os.Stdin)

	knownAddresess = make(map[int]bool, 1)
	myAddress = os.Getpid()
	log.Println("My address is ", myAddress)
	msg := message.NewVoteMessage(myAddress)
	mm, _ := xml.Marshal(msg)
	fmt.Println(string(mm))
	listenMulticast = conn
	writeMulticast = lconn
	multicastAddr = mcaddr
	go listen(listenMulticast)
	go startVoting()
	for {
		// Sleep 20 seconds to give time to spawn more clients
		// time.Sleep(time.Second * 10)
		txt, _, err := reader.ReadLine()
		b := make([]byte, 256)
		copy(b, txt)
		check(err)
		_, err = writeMulticast.WriteToUDP(b, mcaddr)
		check(err)
	}
}
示例#19
0
文件: peer.go 项目: jerluc/pir
// Subscribe subscribes a peer to a group. By subscribing to a group, a peer
// receives global updates of group membership across the network.
func (p *Peer) Subscribe(group *Group) {
	groupConn, err := net.ListenMulticastUDP("udp", nil, group.BroadcastAddress)
	if err != nil {
		log.Fatal(err)
	}

	log.Infof("Subscribed to group [ %s ]", group)
	for {
		buffer := make([]byte, UDPBufferSize)
		fill, _, err := groupConn.ReadFromUDP(buffer)
		if err != nil {
			log.Fatal(err)
		}

		payload := string(buffer[:fill])

		peer, belongsToGroup, parseErr := p.parsePeerBroadcast(group, payload)
		if parseErr != nil {
			log.Warn("Could not handle broadcast:", parseErr)
		}

		if belongsToGroup && peer.ID != p.ID {
			group.AddPeer(peer)
		}
	}
}
示例#20
0
func (b *Beacon) setupListener() {
	var ip net.IP
	ip = net.IPv4(224, 0, 0, 1)

	b.logger.Printf("Listen Address is %s", ip)

	ifis, _ := net.Interfaces()
	var ifi net.Interface
	for _, ifi = range ifis {
		if ifi.Flags&net.FlagMulticast == net.FlagMulticast {
			break
		}
	}

	var err error
	b.listenConn, err = net.ListenMulticastUDP("udp4", &ifi, &net.UDPAddr{
		IP:   ip,
		Port: b.conf.Port,
	})

	if err != nil {
		b.logger.Fatalf("Failed to setup beacon", err)
	}
	return
}
示例#21
0
文件: main.go 项目: soh335/go-mdns
func (c *Client) Discover(domain string, cb func(*dns.Msg)) {
	m := new(dns.Msg)
	m.SetQuestion(dns.Fqdn(domain), dns.TypePTR)
	m.RecursionDesired = true

	addr := &net.UDPAddr{
		IP:   net.ParseIP("224.0.0.251"),
		Port: 5353,
	}

	conn, err := net.ListenMulticastUDP("udp4", nil, addr)

	if err != nil {
		panic(err)
	}

	defer conn.Close()
	c.conn = conn

	out, err := m.Pack()

	if err != nil {
		panic(err)
	}

	_, err = conn.WriteToUDP(out, addr)
	if err != nil {
		panic(err)
	}

	c.handleReceiveMsg(domain, cb)
}
示例#22
0
文件: dell.go 项目: Grayda/go-dell
// Listen listens on port 9131 for projectors
func Listen() (bool, error) {
	var err error
	// Resolve our address, ready for listening. We're listening on port 9131 on the multicast address below
	udpAddr, err = net.ResolveUDPAddr("udp4", "239.255.250.250:9131") // Get our address ready for listening
	if err != nil {
		// Errors. Errors everywhere.
		return false, err
	}

	// Now we're actually listening
	udpConn, err = net.ListenMulticastUDP("udp", nil, udpAddr) // Now we listen on the address we just resolved
	if err != nil {
		return false, err
	}

	passMessage("listening", Projector{})
	// Because we need to be on the lookout for incoming projector discovery packets, we run
	// this in a goroutine and loop forever

	for {

		readUDP()
		// for _, p := range Projectors {
		// 	go readTCP(p)
		// }

	}

	return true, nil
}
示例#23
0
func (this *MulticastServer) Run() {
	var err error
	this.address, err = net.ResolveUDPAddr("udp4", this.addressStr)
	if err != nil {
		panic(err)
	}
	this.connection, err = net.ListenMulticastUDP("udp4", nil, this.address)
	if err != nil {
		panic(err)
	}

	go this.processMessage()

	cache := make([]byte, MAX_PACKAGE_LENGTH)
	for {
		n, _, err := this.connection.ReadFromUDP(cache[0:])
		if err != nil {
			continue
		}

		data := make([]byte, n)
		copy(data[0:n], cache[0:n])

		this.messages <- data
	}

	panic("unreachable")
}
示例#24
0
文件: udp.go 项目: go-on/osc
// ListenMulticastUDP listens for OSC messages
// addressed to the multicast group gaddr on the
// interface ifi.
// See https://golang.org/pkg/net/#ListenMulticastUDP.
func ListenMulticastUDP(network string, ifi *net.Interface, gaddr *net.UDPAddr) (*UDPConn, error) {
	conn, err := net.ListenMulticastUDP(network, ifi, gaddr)
	if err != nil {
		return nil, err
	}
	return &UDPConn{UDPConn: conn}, nil
}
示例#25
0
文件: main.go 项目: leominov/udp-test
func main() {
	var (
		laddr  *net.UDPAddr
		mcaddr *net.UDPAddr

		conn  *net.UDPConn
		lconn *net.UDPConn

		err error
	)

	laddr, err = net.ResolveUDPAddr("udp", ":0")
	if err != nil {
		logrus.Panicf("Error resolving UDP address with %v", err)
	}

	mcaddr, err = net.ResolveUDPAddr("udp", "239.255.2.122:1234")
	if err != nil {
		logrus.Panicf("Error resolving UDP address with %v", err)
	}

	conn, err = net.ListenMulticastUDP("udp", nil, mcaddr)
	if err != nil {
		logrus.Panic(err)
	}

	lconn, err = net.ListenUDP("udp", laddr)
	if err != nil {
		logrus.Panic(err)
	}

	go listen(conn)
	go write(conn, lconn, mcaddr)
}
示例#26
0
文件: main.go 项目: jBugman/optitrack
func record() error {
	log.Println("Recording packets")
	conn, err := net.ListenMulticastUDP("udp4", nil, address())
	if err != nil {
		return err
	}
	defer conn.Close()
	filename := time.Now().Format("2005-01-02_15-04.bin")
	outfile, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer outfile.Close()
	defer outfile.Sync()

	recieved := 0
	buf := make([]byte, bufferSize)
	for i := 0; true; i++ {
		n, _, err := conn.ReadFromUDP(buf)
		if err != nil {
			return err
		}
		outfile.Write(buf)
		recieved += n
		if i%100 == 0 {
			log.Printf("Recieved %d bytes\n", recieved)
		}
	}
	return nil
}
示例#27
0
文件: talk.go 项目: rdallman/dropbit
func listen(msg chan *UDPMessage) {
	me, err := net.ResolveUDPAddr("udp", ":"+strconv.Itoa(*port))
	check(err)
	mcast, err := net.ResolveUDPAddr("udp", "239.192.0.0:3838")
	check(err)
	lan, err := net.ListenMulticastUDP("udp", nil, mcast)
	check(err)
	sock, err := net.ListenUDP("udp", me)
	check(err)
	sock.SetReadBuffer(1 << 16) //64K
	check(err)

	l := func(c *net.UDPConn) {
		for {
			b := make([]byte, 65000)
			_, addr, err := c.ReadFromUDP(b)
			if err != nil {
				continue
			}
			msg <- &UDPMessage{addr, b}
		}
	}
	go l(lan)
	go l(sock)
}
示例#28
0
func NewMulticast(addr, ifname string) (*Multicast, error) {
	gaddr, err := net.ResolveUDPAddr("udp6", addr)
	if err != nil {
		return nil, err
	}
	intf, err := net.InterfaceByName(ifname)
	if err != nil {
		return nil, err
	}
	conn, err := net.ListenMulticastUDP("udp6", intf, gaddr)
	if err != nil {
		return nil, err
	}
	b := &Multicast{
		conn:   conn,
		addr:   gaddr,
		intf:   intf,
		inbox:  make(chan []byte),
		outbox: make(chan recv, 16),
	}

	go genericReader(b.conn, b.outbox)
	go b.writer()

	return b, nil
}
示例#29
0
文件: udp.go 项目: ziutek/dvb
func ListenMulticastUDP(group string, pids ...int16) (ts.PktReader, error) {
	var interf string
	if n := strings.IndexByte(group, '@'); n >= 0 {
		interf = group[n+1:]
		group = group[:n]
	}
	gaddr, err := net.ResolveUDPAddr("udp", group)
	if err != nil {
		return nil, err
	}
	if !gaddr.IP.IsMulticast() {
		return nil, ErrNotMulticast
	}
	ifi, err := net.InterfaceByName(interf)
	if err != nil {
		return nil, err
	}
	c, err := net.ListenMulticastUDP("udp", ifi, gaddr)
	if err != nil {
		return nil, err
	}
	err = c.SetReadBuffer(2 * 1024 * 1024)
	if err != nil {
		return nil, err
	}
	return &PidFilter{
		r:    ts.NewPktPktReader(c, make([]byte, 7*ts.PktLen)),
		pids: pids,
	}, nil
}
示例#30
0
// set up the multicast listener
func MulticastListener(es eventsource.EventSource) {
	// now try to listen to our specific group
	intf, err := net.InterfaceByName("eth0")
	if err != nil {
		log.Fatal(err)
	}
	mcaddr, err := net.ResolveUDPAddr("udp", multicastAddr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Listening on interface %s\n", intf.HardwareAddr)
	conn, err := net.ListenMulticastUDP("udp", intf, mcaddr)
	if err != nil {
		log.Fatal(err)
	}
	addrs, err := intf.MulticastAddrs()
	if err != nil {
		log.Fatal(err)
	}
	for i := 0; i < len(addrs); i++ {
		fmt.Printf("%s\n", addrs[i])
	}

	go doListen(conn, es)
}