Ejemplo n.º 1
0
func MultiaddrsFromServiceEntry(en *mdns.ServiceEntry) [][]byte {
	var addrs []ma.Multiaddr

	// Parse IP addresses
	addr, err := manet.FromIP(en.AddrV4)
	if err == nil {
		addrs = append(addrs, addr)
	}
	addr, err = manet.FromIP(en.AddrV6)
	if err == nil {
		addrs = append(addrs, addr)
	}

	var bytes [][]byte
	for _, addr := range addrs {
		// Append port
		prt, err := ma.NewMultiaddr(fmt.Sprintf("/tcp/%d", en.Port))
		if err != nil {
			continue
		}
		addr = addr.Encapsulate(prt)

		bytes = append(bytes, addr.Bytes())
	}

	return bytes
}
Ejemplo n.º 2
0
func (m *mapping) ExternalAddr() (ma.Multiaddr, error) {
	if time.Now().Sub(m.cacheTime) < CacheTime {
		return m.cached, nil
	}

	if m.ExternalPort() == 0 { // dont even try right now.
		return nil, ErrNoMapping
	}

	ip, err := m.nat.nat.GetExternalAddress()
	if err != nil {
		return nil, err
	}

	ipmaddr, err := manet.FromIP(ip)
	if err != nil {
		return nil, fmt.Errorf("error parsing ip")
	}

	// call m.ExternalPort again, as mapping may have changed under our feet. (tocttou)
	extport := m.ExternalPort()
	if extport == 0 {
		return nil, ErrNoMapping
	}

	tcp, err := ma.NewMultiaddr(fmt.Sprintf("/%s/%d", m.Protocol(), extport))
	if err != nil {
		return nil, err
	}

	maddr2 := ipmaddr.Encapsulate(tcp)

	m.cached = maddr2
	m.cacheTime = time.Now()
	return maddr2, nil
}