當前位置: 首頁>>代碼示例>>Golang>>正文


Golang TCPAddr.String方法代碼示例

本文整理匯總了Golang中net.TCPAddr.String方法的典型用法代碼示例。如果您正苦於以下問題:Golang TCPAddr.String方法的具體用法?Golang TCPAddr.String怎麽用?Golang TCPAddr.String使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在net.TCPAddr的用法示例。


在下文中一共展示了TCPAddr.String方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: DialTCP

func (p *httpProxyClient) DialTCP(network string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
	if laddr != nil || laddr.Port != 0 {
		return nil, errors.New("代理協議不支持指定本地地址。")
	}

	return p.DialTCPSAddr(network, raddr.String())
}
開發者ID:jannson,項目名稱:ProxyClient,代碼行數:7,代碼來源:httpproxy.go

示例2: sendAndReceiveState

// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: m.config.TCPPort}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[INFO] Initiating push/pull sync with: %s", conn.RemoteAddr())

	// Send our state
	if err := m.sendLocalState(conn); err != nil {
		return nil, nil, err
	}

	// Read remote state
	remote, userState, err := m.readRemoteState(conn)
	if err != nil {
		err := fmt.Errorf("Reading remote state failed: %v", err)
		return nil, nil, err
	}

	// Return the remote state
	return remote, userState, nil
}
開發者ID:kainosnoema,項目名稱:memberlist,代碼行數:27,代碼來源:net.go

示例3: sendAndReceiveState

// sendAndReceiveState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: int(port)}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
	metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)

	// Send our state
	if err := m.sendLocalState(conn, join); err != nil {
		return nil, nil, err
	}

	conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
	msgType, bufConn, dec, err := m.readTCP(conn)
	if err != nil {
		return nil, nil, err
	}

	// Quit if not push/pull
	if msgType != pushPullMsg {
		err := fmt.Errorf("received invalid msgType (%d), expected pushPullMsg (%d) %s", msgType, pushPullMsg, LogConn(conn))
		return nil, nil, err
	}

	// Read remote state
	_, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
	return remoteNodes, userState, err
}
開發者ID:PagerDuty,項目名稱:nomad,代碼行數:34,代碼來源:net.go

示例4: detailedOutput

// detailedOutput is used to dump all known information about nodes in
// their raw format
func (c *MembersCommand) detailedOutput(members []agent.Member) []string {
	result := make([]string, 0, len(members))
	header := "Node|Address|Status|Tags"
	result = append(result, header)
	for _, member := range members {
		// Get the tags sorted by key
		tagKeys := make([]string, 0, len(member.Tags))
		for key := range member.Tags {
			tagKeys = append(tagKeys, key)
		}
		sort.Strings(tagKeys)

		// Format the tags as tag1=v1,tag2=v2,...
		var tagPairs []string
		for _, key := range tagKeys {
			tagPairs = append(tagPairs, fmt.Sprintf("%s=%s", key, member.Tags[key]))
		}

		tags := strings.Join(tagPairs, ",")

		addr := net.TCPAddr{IP: member.Addr, Port: int(member.Port)}
		line := fmt.Sprintf("%s|%s|%s|%s",
			member.Name, addr.String(), member.Status, tags)
		result = append(result, line)
	}
	return result
}
開發者ID:faiq,項目名稱:consul,代碼行數:29,代碼來源:members.go

示例5: removeDeadFinger

func (thisNode *node) removeDeadFinger(deadAddress *net.TCPAddr) {
	// If a connected node disappears, remove it from the finger table.
	var closestFinger *net.TCPAddr
	for _, entry := range thisNode.fingerTable {
		if entry.fingerAddress != nil && entry.fingerAddress.String() == deadAddress.String() {
			entry.fingerAddress = nil
		} else if entry.fingerAddress != nil && closestFinger == nil {
			closestFinger = entry.fingerAddress
		}
	}
	// If it's the predecessor, remove it.
	if thisNode.predecessorAddress.String() == deadAddress.String() {
		thisNode.predecessorAddress = nil
	}
	// If there was some other finger, replace it.
	if closestFinger != nil {
		thisNode.SetSuccessor(closestFinger)
	} else if thisNode.predecessorAddress != nil {
		// There was no other finger in the table, but maybe as a predecessor?
		thisNode.SetSuccessor(thisNode.predecessorAddress)
	} else {
		// If not, become a singular node ring.
		thisNode.MakeIntoRing()
	}
}
開發者ID:davnym-4,項目名稱:ackord,代碼行數:25,代碼來源:fingertable.go

示例6: GetOriginalDst

// GetOriginalDst returns original destination of Conn
func GetOriginalDst(c net.Conn) (string, error) {
	tcp, ok := c.(*net.TCPConn)
	if !ok {
		return "", errors.New("socket is not tcp")
	}
	file, err := tcp.File()
	if err != nil {
		return "", err
	}
	defer file.Close()
	sa, err := syscall.Getsockname(int(file.Fd()))
	if err != nil {
		return "", err
	}

	var addr net.TCPAddr
	if v, ok := sa.(*syscall.SockaddrInet4); ok {
		addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port}
	} else if v, ok := sa.(*syscall.SockaddrInet6); ok {
		addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port, Zone: zoneToString(int(v.ZoneId))}
	} else {
		return "", errors.New("socket is not ipv4")
	}
	return addr.String(), nil
}
開發者ID:nyushi,項目名稱:traproxy,代碼行數:26,代碼來源:orgdst_darwin.go

示例7: makeNewNode

func makeNewNode(host string, port int) (*node, error) {
	var (
		resolvedAddress *net.TCPAddr
		err             error
	)
	if resolvedAddress, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(host, strconv.Itoa(port))); err != nil {
		return nil, err
	}
	newNode := new(node)
	newNode.SetAddress(resolvedAddress)
	if host == "" {
		return nil, ErrNotYetImplemented
	} else {
		newNode.baseKey = hashString(resolvedAddress.String())
	}
	entries := M()
	newNode.fingerTable = make([]*tableEntry, entries, entries)
	for row := 0; row < entries; row++ {
		newNode.SetTableEntry(row, nil)
	}
	newNode.dataStorage = make(map[string][]byte)
	newNode.backupStorageOfPredecessorsData = make(map[string][]byte)
	newNode.backupStorageOfSuccessorsData = make(map[string][]byte)
	newNode.aliasStorage = make(map[string]string)
	newNode.backupStorageOfPredecessorsAliases = make(map[string]string)
	newNode.backupStorageOfSuccessorsAliases = make(map[string]string)
	newNode.wgs = new(waitGroups)
	return newNode, nil
}
開發者ID:davnym-4,項目名稱:ackord,代碼行數:29,代碼來源:node_init.go

示例8: sendAndReceiveState

// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
	// Attempt to connect
	dialer := net.Dialer{Timeout: m.config.TCPTimeout}
	dest := net.TCPAddr{IP: addr, Port: int(port)}
	conn, err := dialer.Dial("tcp", dest.String())
	if err != nil {
		return nil, nil, err
	}
	defer conn.Close()
	m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
	metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)

	// Send our state
	if err := m.sendLocalState(conn, join); err != nil {
		return nil, nil, err
	}

	// Read remote state
	_, remote, userState, err := m.readRemoteState(conn)
	if err != nil {
		err := fmt.Errorf("Reading remote state failed: %v", err)
		return nil, nil, err
	}

	// Return the remote state
	return remote, userState, nil
}
開發者ID:DaveDaCoda,項目名稱:docker,代碼行數:28,代碼來源:net.go

示例9: replyAnnouncePeer

func (d *DHT) replyAnnouncePeer(addr net.UDPAddr, node *remoteNode, r responseType) {
	ih := InfoHash(r.A.InfoHash)
	if log.V(3) {
		log.Infof("DHT: announce_peer. Host %v, nodeID: %x, infoHash: %x, peerPort %d, distance to me %x",
			addr, r.A.Id, ih, r.A.Port, hashDistance(ih, InfoHash(d.nodeId)),
		)
	}
	// node can be nil if, for example, the server just restarted and received an announce_peer
	// from a node it doesn't yet know about.
	if node != nil && d.checkToken(addr, r.A.Token) {
		peerAddr := net.TCPAddr{IP: addr.IP, Port: r.A.Port}
		d.peerStore.addContact(ih, nettools.DottedPortToBinary(peerAddr.String()))
		// Allow searching this node immediately, since it's telling us
		// it has an infohash. Enables faster upgrade of other nodes to
		// "peer" of an infohash, if the announcement is valid.
		node.lastResponseTime = time.Now().Add(-searchRetryPeriod)
		if d.peerStore.hasLocalDownload(ih) {
			d.PeersRequestResults <- map[InfoHash][]string{ih: []string{nettools.DottedPortToBinary(peerAddr.String())}}
		}
	}
	// Always reply positively. jech says this is to avoid "back-tracking", not sure what that means.
	reply := replyMessage{
		T: r.T,
		Y: "r",
		R: map[string]interface{}{"id": d.nodeId},
	}
	sendMsg(d.conn, addr, reply)
}
開發者ID:peterlee2008,項目名稱:dht,代碼行數:28,代碼來源:dht.go

示例10: interfaceURLs

// Generate all publishable URLs for a given HTTP port.
func interfaceURLs(port int) (types.URLs, error) {
	allAddrs, err := net.InterfaceAddrs()
	if err != nil {
		return []url.URL{}, err
	}

	var allURLs types.URLs
	for _, a := range allAddrs {
		ip, ok := a.(*net.IPNet)
		if !ok || !ip.IP.IsGlobalUnicast() {
			continue
		}

		tcp := net.TCPAddr{
			IP:   ip.IP,
			Port: port,
		}

		u := url.URL{
			Scheme: "http",
			Host:   tcp.String(),
		}
		allURLs = append(allURLs, u)
	}

	if len(allAddrs) == 0 {
		return []url.URL{}, fmt.Errorf("no publishable addresses")
	}

	return allURLs, nil
}
開發者ID:safchain,項目名稱:skydive,代碼行數:32,代碼來源:etcd.go

示例11: CreateTCPSocket

func CreateTCPSocket(proto, addr string) (net.Listener, error) {
	var err error
	var laddr *net.TCPAddr

	laddr, err = net.ResolveTCPAddr(proto, addr)
	if err != nil {
		return nil, err
	}

	family, ipv6only := favoriteTCPAddrFamily(proto, laddr, "listen")

	var socketAddr syscall.Sockaddr
	if socketAddr, err = ipToSockaddr(family, laddr.IP, laddr.Port, laddr.Zone); err != nil {
		panic(err)
		return nil, err
	}

	var s int
	if s, err = sysSocket(family, syscall.SOCK_STREAM, 0); err != nil {
		return nil, err
	}

	if err = setDefaultSockopts(s, family, syscall.SOCK_STREAM, ipv6only); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = setDefaultListenerSockopts(s); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = syscall.SetsockoptInt(s, syscall.SOL_SOCKET, SO_REUSEPORT, 1); err != nil {
		closesocket(s)
		panic(err)
		return nil, err
	}

	if err = syscall.Bind(s, socketAddr); err != nil {
		closesocket(s)
		return nil, err
	}

	if err = syscall.Listen(s, maxListenerBacklog()); err != nil {
		closesocket(s)
		return nil, err
	}

	file := os.NewFile(uintptr(s), "listener-"+laddr.String())
	defer file.Close()

	var socketListener net.Listener
	if socketListener, err = net.FileListener(file); err != nil {
		return nil, err
	}

	return socketListener, nil

}
開發者ID:htee,項目名稱:hteed,代碼行數:59,代碼來源:socket.go

示例12: mustConnectGFW

func mustConnectGFW(tcpAddr *net.TCPAddr) (net.Conn, error) {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		return nil, err
	}
	conn.Write([]byte("  V1"))
	return conn, nil
}
開發者ID:pengswift,項目名稱:gfw,代碼行數:8,代碼來源:protocol_v1_test.go

示例13: mustConnectLookupd

func mustConnectLookupd(t *testing.T, tcpAddr *net.TCPAddr) net.Conn {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		t.Fatal("failed to connect to lookupd")
	}
	conn.Write(nsq.MagicV1)
	return conn
}
開發者ID:zhangyuchen0411,項目名稱:nsq,代碼行數:8,代碼來源:nsqlookupd_test.go

示例14: mustConnectNSQD

func mustConnectNSQD(tcpAddr *net.TCPAddr) (net.Conn, error) {
	conn, err := net.DialTimeout("tcp", tcpAddr.String(), time.Second)
	if err != nil {
		return nil, err
	}
	conn.Write(nsq.MagicV2)
	return conn, nil
}
開發者ID:nguyenducnhaty,項目名稱:nsq,代碼行數:8,代碼來源:protocol_v2_test.go

示例15: isTCPIPv6

// No routine in package net to test if an address is v4 or v6?
func isTCPIPv6(address *net.TCPAddr) bool {
	if strings.HasPrefix(address.String(), "<nil>") {
		return false
	} else {
		return (address.String()[0] == '[')
	}
	return false // Should never arrive here
}
開發者ID:bortzmeyer,項目名稱:nonewcontent,代碼行數:9,代碼來源:nonewcontent.go


注:本文中的net.TCPAddr.String方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。