• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang go-multiaddr.Multiaddr类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/jbenet/go-multiaddr.Multiaddr的典型用法代码示例。如果您正苦于以下问题:Golang Multiaddr类的具体用法?Golang Multiaddr怎么用?Golang Multiaddr使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Multiaddr类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Add

func (oas *ObservedAddrSet) Add(addr ma.Multiaddr, observer ma.Multiaddr) {
	oas.Lock()
	defer oas.Unlock()

	// for zero-value.
	if oas.addrs == nil {
		oas.addrs = make(map[string]*ObservedAddr)
		oas.ttl = peer.OwnObservedAddrTTL
	}

	s := addr.String()
	oa, found := oas.addrs[s]

	// first time seeing address.
	if !found {
		oa = &ObservedAddr{
			Addr:   addr,
			SeenBy: make(map[string]struct{}),
		}
		oas.addrs[s] = oa
	}

	// mark the observer
	oa.SeenBy[observerGroup(observer)] = struct{}{}
	oa.LastSeen = time.Now()
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:26,代码来源:obsaddr.go


示例2: AddrMatch

// AddrMatch returns the Multiaddrs that match the protocol stack on addr
func AddrMatch(match ma.Multiaddr, addrs []ma.Multiaddr) []ma.Multiaddr {

	// we should match transports entirely.
	p1s := match.Protocols()

	out := make([]ma.Multiaddr, 0, len(addrs))
	for _, a := range addrs {
		p2s := a.Protocols()
		if len(p1s) != len(p2s) {
			continue
		}

		match := true
		for i, p2 := range p2s {
			if p1s[i].Code != p2.Code {
				match = false
				break
			}
		}
		if match {
			out = append(out, a)
		}
	}
	return out
}
开发者ID:Gaboose,项目名称:go-pubsub,代码行数:26,代码来源:net.go


示例3: DialArgs

// DialArgs is a convenience function returning arguments for use in net.Dial
func DialArgs(m ma.Multiaddr) (string, string, error) {
	if !IsThinWaist(m) {
		return "", "", fmt.Errorf("%s is not a 'thin waist' address", m)
	}

	str := m.String()
	parts := strings.Split(str, "/")[1:]

	if len(parts) == 2 { // only IP
		return parts[0], parts[1], nil
	}

	network := parts[2]
	if parts[2] == "udp" && len(parts) > 4 && parts[4] == "utp" {
		network = parts[4]
	}

	var host string
	switch parts[0] {
	case "ip4":
		network = network + "4"
		host = strings.Join([]string{parts[1], parts[3]}, ":")
	case "ip6":
		network = network + "6"
		host = fmt.Sprintf("[%s]:%s", parts[1], parts[3])
	}
	return network, host, nil
}
开发者ID:Gaboose,项目名称:go-pubsub,代码行数:29,代码来源:convert.go


示例4: Dialer

func (t *TcpTransport) Dialer(laddr ma.Multiaddr, opts ...DialOpt) (Dialer, error) {
	t.dlock.Lock()
	defer t.dlock.Unlock()
	s := laddr.String()
	d, found := t.dialers[s]
	if found {
		return d, nil
	}
	var base manet.Dialer

	var doReuse bool
	for _, o := range opts {
		switch o := o.(type) {
		case TimeoutOpt:
			base.Timeout = time.Duration(o)
		case ReuseportOpt:
			doReuse = bool(o)
		default:
			return nil, fmt.Errorf("unrecognized option: %#v", o)
		}
	}

	tcpd, err := t.newTcpDialer(base, laddr, doReuse)
	if err != nil {
		return nil, err
	}

	t.dialers[s] = tcpd
	return tcpd, nil
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:30,代码来源:tcp.go


示例5: ResolveUnspecifiedAddress

// ResolveUnspecifiedAddress expands an unspecified ip addresses (/ip4/0.0.0.0, /ip6/::) to
// use the known local interfaces. If ifaceAddr is nil, we request interface addresses
// from the network stack. (this is so you can provide a cached value if resolving many addrs)
func ResolveUnspecifiedAddress(resolve ma.Multiaddr, ifaceAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {
	// split address into its components
	split := ma.Split(resolve)

	// if first component (ip) is not unspecified, use it as is.
	if !manet.IsIPUnspecified(split[0]) {
		return []ma.Multiaddr{resolve}, nil
	}

	out := make([]ma.Multiaddr, 0, len(ifaceAddrs))
	for _, ia := range ifaceAddrs {
		// must match the first protocol to be resolve.
		if ia.Protocols()[0].Code != resolve.Protocols()[0].Code {
			continue
		}

		split[0] = ia
		joined := ma.Join(split...)
		out = append(out, joined)
		log.Debug("adding resolved addr:", resolve, joined, out)
	}
	if len(out) < 1 {
		return nil, fmt.Errorf("failed to resolve: %s", resolve)
	}
	return out, nil
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:29,代码来源:addr.go


示例6: Apply

func (_ IP) Apply(m ma.Multiaddr, side int, ctx match.Context) error {
	p := m.Protocols()[0]
	name := p.Name
	s, _ := m.ValueForProtocol(p.Code)

	mctx := ctx.Misc()
	ip := net.ParseIP(s)
	if ip == nil {
		return fmt.Errorf("incorrect ip %s", m)
	}

	switch name {
	case "ip4":
		if ip = ip.To4(); ip == nil {
			return fmt.Errorf("incorrect ip4 %s", m)
		}
	case "ip6":
		if ip = ip.To16(); ip == nil {
			return fmt.Errorf("incorrent ip6 %s", m)
		}
	}

	mctx.IPs = append(mctx.IPs, ip)
	return nil
}
开发者ID:Gaboose,项目名称:go-multiaddr-net,代码行数:25,代码来源:ip.go


示例7: assertEcho

func assertEcho(t *testing.T, rwc io.ReadWriteCloser, m ma.Multiaddr) {
	str := "test string"
	done := make(chan struct{})
	defer rwc.Close()

	go func() {
		defer close(done)

		_, err := fmt.Fprint(rwc, str)
		if err != nil {
			t.Error(err)
			return
		}

		buf := make([]byte, 256)
		n, err := rwc.Read(buf)
		if err != nil {
			t.Error(err)
			return
		}
		got := string(buf[:n])

		if got != str {
			t.Errorf("expected \"%s\", got \"%s\"", str, got)
		}
	}()

	select {
	case <-done:
	case <-time.After(time.Second):
		t.Errorf("assertEcho: %s timed out", m.String())
	}
}
开发者ID:Gaboose,项目名称:manet-echo,代码行数:33,代码来源:net_test.go


示例8: AddrInList

// AddrInList returns whether or not an address is part of a list.
// this is useful to check if NAT is happening (or other bugs?)
func AddrInList(addr ma.Multiaddr, list []ma.Multiaddr) bool {
	for _, addr2 := range list {
		if addr.Equal(addr2) {
			return true
		}
	}
	return false
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:10,代码来源:addr.go


示例9: addrInAddrs

func addrInAddrs(a ma.Multiaddr, as []ma.Multiaddr) bool {
	for _, b := range as {
		if a.Equal(b) {
			return true
		}
	}
	return false
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:8,代码来源:id.go


示例10: Apply

func (w WS) Apply(m ma.Multiaddr, side int, ctx Context) error {
	var path string
	// ws client matches /http/ws too, so /ws might not be the first protocol
	for _, p := range m.Protocols() {
		if p.Name == "ws" {
			pth, err := m.ValueForProtocol(p.Code)
			if err != nil {
				return err
			}
			path = pth
			break
		}
	}
	sctx := ctx.Special()
	mctx := ctx.Misc()

	switch side {

	case S_Client:
		// resolve url
		var url string
		if mctx.Host != "" {
			// this will make mctx.Host appear in http request headers,
			// cloud servers often require that
			url = fmt.Sprintf("ws://%s/%s", mctx.Host, path)
		} else {
			switch t := sctx.NetConn.(type) {
			case *net.TCPConn:
				url = fmt.Sprintf("ws://%s/%s", t.RemoteAddr().String(), path)
			default:
				url = fmt.Sprintf("ws://foo.bar/%s", path)
			}
		}

		wcon, err := w.Select(sctx.NetConn, url)
		if err != nil {
			return err
		}
		sctx.NetConn = wcon
		return nil

	case S_Server:
		if mctx.HTTPMux == nil {
			// help the user out if /http is missing before /ws
			HTTP{}.Apply(m, S_Server, ctx)
		}
		ln, err := w.Handle(mctx.HTTPMux, "/"+path)
		if err != nil {
			return err
		}
		sctx.NetListener = ln
		sctx.CloseFn = ConcatClose(ln.Close, sctx.CloseFn)
		return nil

	}

	return fmt.Errorf("incorrect side constant")
}
开发者ID:Gaboose,项目名称:manet-echo,代码行数:58,代码来源:ws.go


示例11: CheckNATWarning

// CheckNATWarning checks if our observed addresses differ. if so,
// informs the user that certain things might not work yet
func CheckNATWarning(observed, expected ma.Multiaddr, listen []ma.Multiaddr) {
	if observed.Equal(expected) {
		return
	}

	if !AddrInList(observed, listen) { // probably a nat
		log.Warningf(natWarning, observed, listen)
	}
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:11,代码来源:addr.go


示例12: Match

func (_ DNS) Match(m ma.Multiaddr, side int) (int, bool) {
	ps := m.Protocols()

	if len(ps) > 0 && ps[0].Name == "dns" {
		return 1, true
	}

	return 0, false
}
开发者ID:Gaboose,项目名称:go-multiaddr-net,代码行数:9,代码来源:dns.go


示例13: trimPrefix

func trimPrefix(m, prem ma.Multiaddr) (ma.Multiaddr, bool) {
	s := m.String()
	pres := prem.String()

	if !strings.HasPrefix(s, pres) {
		return nil, false
	}

	return ma.StringCast(strings.TrimPrefix(s, pres)), true
}
开发者ID:Gaboose,项目名称:go-multiaddr-net,代码行数:10,代码来源:net.go


示例14: Match

func (p HTTP) Match(m ma.Multiaddr, side int) (int, bool) {
	if side != S_Server {
		return 0, false
	}

	ms := m.Protocols()
	if len(ms) >= 1 && ms[0].Name == "http" {
		return 1, true
	}

	return 0, false
}
开发者ID:Gaboose,项目名称:manet-echo,代码行数:12,代码来源:http.go


示例15: Match

func (t TCP) Match(m ma.Multiaddr, side int) (int, bool) {
	ps := m.Protocols()

	if len(ps) < 1 {
		return 0, false
	}

	if ps[0].Name == "tcp" {
		return 1, true
	}

	return 0, false
}
开发者ID:Gaboose,项目名称:go-multiaddr-net,代码行数:13,代码来源:tcp.go


示例16: rawConnDial

// rawConnDial dials the underlying net.Conn + manet.Conns
func (d *Dialer) rawConnDial(ctx context.Context, raddr ma.Multiaddr, remote peer.ID) (transport.Conn, error) {
	if strings.HasPrefix(raddr.String(), "/ip4/0.0.0.0") {
		log.Event(ctx, "connDialZeroAddr", lgbl.Dial("conn", d.LocalPeer, remote, nil, raddr))
		return nil, fmt.Errorf("Attempted to connect to zero address: %s", raddr)
	}

	sd := d.subDialerForAddr(raddr)
	if sd == nil {
		return nil, fmt.Errorf("no dialer for %s", raddr)
	}

	return sd.Dial(raddr)
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:14,代码来源:dial.go


示例17: Match

func (_ IP) Match(m ma.Multiaddr, side int) (int, bool) {
	ps := m.Protocols()

	if len(ps) < 1 {
		return 0, false
	}

	name := ps[0].Name
	if name == "ip" || name == "ip4" || name == "ip6" {
		return 1, true
	}

	return 0, false
}
开发者ID:Gaboose,项目名称:go-multiaddr-net,代码行数:14,代码来源:ip.go


示例18: IsIPLoopback

// IsIPLoopback returns whether a Multiaddr is a "Loopback" IP address
// This means either /ip4/127.0.0.1 or /ip6/::1
// TODO: differentiate IsIPLoopback and OverIPLoopback
func IsIPLoopback(m ma.Multiaddr) bool {
	b := m.Bytes()

	// /ip4/127 prefix (_entire_ /8 is loopback...)
	if bytes.HasPrefix(b, []byte{ma.P_IP4, 127}) {
		return true
	}

	// /ip6/::1
	if IP6Loopback.Equal(m) || IP6LinkLocalLoopback.Equal(m) {
		return true
	}

	return false
}
开发者ID:Gaboose,项目名称:go-pubsub,代码行数:18,代码来源:ip.go


示例19: addPortMapping

func addPortMapping(nmgr *natManager, intaddr ma.Multiaddr) {
	nat := nmgr.NAT()
	if nat == nil {
		panic("natManager addPortMapping called without a nat.")
	}

	// first, check if the port mapping already exists.
	for _, mapping := range nat.Mappings() {
		if mapping.InternalAddr().Equal(intaddr) {
			return // it exists! return.
		}
	}

	ctx := context.TODO()
	lm := make(lgbl.DeferredMap)
	lm["internalAddr"] = func() interface{} { return intaddr.String() }

	defer log.EventBegin(ctx, "natMgrAddPortMappingWait", lm).Done()

	select {
	case <-nmgr.proc.Closing():
		lm["outcome"] = "cancelled"
		return // no use.
	case <-nmgr.ready: // wait until it's ready.
	}

	// actually start the port map (sub-event because waiting may take a while)
	defer log.EventBegin(ctx, "natMgrAddPortMapping", lm).Done()

	// get the nat
	m, err := nat.NewMapping(intaddr)
	if err != nil {
		lm["outcome"] = "failure"
		lm["error"] = err
		return
	}

	extaddr, err := m.ExternalAddr()
	if err != nil {
		lm["outcome"] = "failure"
		lm["error"] = err
		return
	}

	lm["outcome"] = "success"
	lm["externalAddr"] = func() interface{} { return extaddr.String() }
	log.Infof("established nat port mapping: %s <--> %s", intaddr, extaddr)
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:48,代码来源:natmgr.go


示例20: MultiaddrProtocolsMatch

// MultiaddrProtocolsMatch returns whether two multiaddrs match in protocol stacks.
func MultiaddrProtocolsMatch(a, b ma.Multiaddr) bool {
	ap := a.Protocols()
	bp := b.Protocols()

	if len(ap) != len(bp) {
		return false
	}

	for i, api := range ap {
		if api.Code != bp[i].Code {
			return false
		}
	}

	return true
}
开发者ID:tilgovi,项目名称:go-libp2p,代码行数:17,代码来源:dial.go



注:本文中的github.com/jbenet/go-multiaddr.Multiaddr类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang goprocess.Process类代码示例发布时间:2022-05-23
下一篇:
Golang go-multiaddr.NewMultiaddr函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap