github.com/stampzilla/stampzilla-go@v2.0.0-rc9+incompatible/pkg/node/mdns.go (about)

     1  package node
     2  
     3  import (
     4  	"context"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/micro/mdns"
     9  	"github.com/sirupsen/logrus"
    10  )
    11  
    12  //func main() {
    13  //ip, port, err := queryMDNS()
    14  //if err != nil {
    15  //logrus.Error(err)
    16  //return
    17  //}
    18  
    19  //logrus.Infof("Found %s:%d", ip, port)
    20  //}
    21  
    22  func queryMDNS() (string, string) {
    23  	entriesCh := make(chan *mdns.ServiceEntry)
    24  
    25  	logrus.Info("node: running mdns query")
    26  	ctx, cancel := context.WithCancel(context.Background())
    27  	go func() {
    28  		for {
    29  			select {
    30  			case <-ctx.Done():
    31  				return
    32  			default:
    33  				mdns.Lookup("_stampzilla._tcp", entriesCh)
    34  
    35  			}
    36  		}
    37  	}()
    38  
    39  	var entry *mdns.ServiceEntry
    40  	for {
    41  		entry = <-entriesCh
    42  		if strings.Contains(entry.Name, "_stampzilla._tcp") { //Ignore answers that are not what we are looking for
    43  			break
    44  		}
    45  	}
    46  	cancel()
    47  	port := strconv.Itoa(entry.Port)
    48  	logrus.Infof("node: got mdns query response %s:%s", entry.AddrV4.String(), port)
    49  	return entry.AddrV4.String(), port
    50  }