本文整理匯總了Golang中net.Addr類的典型用法代碼示例。如果您正苦於以下問題:Golang Addr類的具體用法?Golang Addr怎麽用?Golang Addr使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Addr類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getConn
// getConn is used to get a connection from the pool
func (n *NetworkTransport) getConn(target net.Addr) (*netConn, error) {
// Check for a pooled conn
if conn := n.getPooledConn(target); conn != nil {
return conn, nil
}
// Dial a new connection
conn, err := n.stream.Dial(target.String(), n.timeout)
if err != nil {
return nil, err
}
// Wrap the conn
netConn := &netConn{
target: target,
conn: conn,
r: bufio.NewReader(conn),
w: bufio.NewWriter(conn),
}
// Setup encoder/decoders
netConn.dec = codec.NewDecoder(netConn.r, &codec.MsgpackHandle{})
netConn.enc = codec.NewEncoder(netConn.w, &codec.MsgpackHandle{})
// Done
return netConn, nil
}
示例2: packetDump
func packetDump(addr net.Addr, data []byte, cache TemplateCache) {
p, err := nf9packet.Decode(data)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
templateList := p.TemplateRecords()
flowSets := p.DataFlowSets()
for _, t := range templateList {
templateKey := fmt.Sprintf("%s|%b|%v", addr.String(), p.SourceId, t.TemplateId)
cache[templateKey] = t
}
for _, set := range flowSets {
templateKey := fmt.Sprintf("%s|%b|%v", addr.String(), p.SourceId, set.Id)
template, ok := cache[templateKey]
if !ok {
// We do not have template for this Data FlowSet yet
continue
}
records := template.DecodeFlowSet(&set)
if records == nil {
// Error in decoding Data FlowSet
continue
}
printTable(template, records)
}
}
示例3: newAuthAddr
// newAuthAddr returns a string from a net.Addr used to index the address the key in our lookup.
func newAuthAddr(addr net.Addr) string {
if addr == nil {
return ""
}
host, _, _ := net.SplitHostPort(addr.String())
return host
}
示例4: New
func (m *connManager) New(addr net.Addr) chan []byte {
reqChan := make(chan []byte, 64) // TODO (better value)
m.Lock()
m.reqMap[addr.String()] = reqChan
m.Unlock()
return reqChan
}
示例5: getBackendConn
func (udp *udpProxySocket) getBackendConn(activeClients *clientCache, cliAddr net.Addr, proxier *Proxier, service proxy.ServicePortName, timeout time.Duration) (net.Conn, error) {
activeClients.mu.Lock()
defer activeClients.mu.Unlock()
svrConn, found := activeClients.clients[cliAddr.String()]
if !found {
// TODO: This could spin up a new goroutine to make the outbound connection,
// and keep accepting inbound traffic.
glog.V(3).Infof("New UDP connection from %s", cliAddr)
var err error
svrConn, err = tryConnect(service, cliAddr, "udp", proxier)
if err != nil {
return nil, err
}
if err = svrConn.SetDeadline(time.Now().Add(timeout)); err != nil {
glog.Errorf("SetDeadline failed: %v", err)
return nil, err
}
activeClients.clients[cliAddr.String()] = svrConn
go func(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, timeout time.Duration) {
defer util.HandleCrash()
udp.proxyClient(cliAddr, svrConn, activeClients, timeout)
}(cliAddr, svrConn, activeClients, timeout)
}
return svrConn, nil
}
示例6: runListener
func runListener(listenPacket listenPacketFunc, port *port, dataChan chan<- []byte, stopChan <-chan struct{}) (err error) {
conn, err := listenPacket(fmt.Sprintf(":%d", port.Get()))
if err != nil {
return
}
port.Set(conn.Port())
go func() {
<-stopChan
conn.Close()
}()
for {
buffer := make([]byte, 4096)
var n int
var addr net.Addr
n, addr, err = conn.ReadFrom(buffer) // errors returned from here are used for control
if err != nil {
return
}
if n == 0 {
log.Printf("Warning: zero bytes read from client: %v\n", addr.String())
} else {
dataChan <- buffer[0:n]
}
}
}
示例7: NewSession
func NewSession(transportDesc string, remoteAddr net.Addr) (s *Session) {
s = &Session{}
// deserialize input data
parts := strings.Split(transportDesc, ";")
s.SessionType = parts[0]
s.SessionMode = parts[1]
paramsMap := map[string]string{}
for _, v := range parts[2:] {
pair := strings.Split(v, "=")
paramsMap[pair[0]] = pair[1]
}
s.ClientPort = strings.Split(paramsMap["client_port"], "-")[0]
// pick a random udp port
ip := strings.Split(remoteAddr.String(), ":")[0]
conn, err := net.Dial("udp", fmt.Sprintf("%s:%s", ip, s.ClientPort))
if err != nil {
fmt.Println(err)
return
}
s.ServerPort = strings.Split(conn.LocalAddr().String(), ":")[1]
s.conn = conn
s.Id = strconv.Itoa(rand.Int())
s.start = time.Now()
sessions[s.Id] = s
return
}
示例8: officialAddr
func officialAddr(unresolvedAddr string, resolvedAddr net.Addr) (*util.UnresolvedAddr, error) {
unresolvedHost, unresolvedPort, err := net.SplitHostPort(unresolvedAddr)
if err != nil {
return nil, err
}
resolvedHost, resolvedPort, err := net.SplitHostPort(resolvedAddr.String())
if err != nil {
return nil, err
}
var host string
if unresolvedHost != "" {
// A host was provided, use it.
host = unresolvedHost
} else {
// A host was not provided. Ask the system, and fall back to the listener.
if hostname, err := os.Hostname(); err == nil {
host = hostname
} else {
host = resolvedHost
}
}
var port string
if unresolvedPort != "0" {
// A port was provided, use it.
port = unresolvedPort
} else {
// A port was not provided, but the system assigned one.
port = resolvedPort
}
return util.NewUnresolvedAddr(resolvedAddr.Network(), net.JoinHostPort(host, port)), nil
}
示例9: Dial
func (ct *codecTransport) Dial(addr net.Addr) (codec.CarrierConn, error) {
c, err := net.Dial("tcp", addr.String())
if err != nil {
return nil, err
}
return newCodecConn(trace.NewFrame("hmac", "dial"), c.(*net.TCPConn), ct.key)
}
示例10: Dial
func (fw *firewall) Dial(addr net.Addr) (net.Conn, error) {
if fw.rule != nil && !fw.rule.Match(addr) {
return nil, &net.OpError{Op: "dial", Net: addr.Network(), Addr: addr, Err: errors.New("unreachable host")}
}
return fw.t.Dial(addr)
}
示例11: start
// start initializes the infostore with the rpc server address and
// then begins processing connecting clients in an infinite select
// loop via goroutine. Periodically, clients connected and awaiting
// the next round of gossip are awoken via the conditional variable.
func (s *server) start(grpcServer *grpc.Server, addr net.Addr) {
s.mu.Lock()
s.is.NodeAddr = util.MakeUnresolvedAddr(addr.Network(), addr.String())
s.mu.Unlock()
RegisterGossipServer(grpcServer, s)
broadcast := func() {
ready := make(chan struct{})
s.mu.Lock()
close(s.ready)
s.ready = ready
s.mu.Unlock()
}
unregister := s.is.registerCallback(".*", func(_ string, _ roachpb.Value) {
broadcast()
})
s.stopper.RunWorker(func() {
<-s.stopper.ShouldDrain()
s.mu.Lock()
unregister()
s.mu.Unlock()
broadcast()
})
}
示例12: startGossipAtAddr
func startGossipAtAddr(
nodeID roachpb.NodeID,
addr net.Addr,
stopper *stop.Stopper,
t *testing.T,
registry *metric.Registry,
) *Gossip {
rpcContext := rpc.NewContext(log.AmbientContext{}, &base.Config{Insecure: true}, nil, stopper)
server := rpc.NewServer(rpcContext)
g := NewTest(nodeID, rpcContext, server, nil, stopper, registry)
ln, err := netutil.ListenAndServeGRPC(stopper, server, addr)
if err != nil {
t.Fatal(err)
}
addr = ln.Addr()
if err := g.SetNodeDescriptor(&roachpb.NodeDescriptor{
NodeID: nodeID,
Address: util.MakeUnresolvedAddr(addr.Network(), addr.String()),
}); err != nil {
t.Fatal(err)
}
g.start(addr)
time.Sleep(time.Millisecond)
return g
}
示例13: EnsureLeader
func (c *cluster) EnsureLeader(t *testing.T, expect net.Addr) {
limit := time.Now().Add(400 * time.Millisecond)
CHECK:
for _, r := range c.rafts {
leader := r.Leader()
if expect == nil {
if leader != nil {
if time.Now().After(limit) {
t.Fatalf("leader %v expected nil", leader)
} else {
goto WAIT
}
}
} else {
if leader == nil || leader.String() != expect.String() {
if time.Now().After(limit) {
t.Fatalf("leader %v expected %v", leader, expect)
} else {
goto WAIT
}
}
}
}
return
WAIT:
time.Sleep(10 * time.Millisecond)
goto CHECK
}
示例14: makeRPC
func (i *InmemTransport) makeRPC(target net.Addr, args interface{}, r io.Reader, timeout time.Duration) (rpcResp RPCResponse, err error) {
i.RLock()
peer, ok := i.peers[target.String()]
i.RUnlock()
if !ok {
err = fmt.Errorf("failed to connect to peer: %v", target)
return
}
// Send the RPC over
respCh := make(chan RPCResponse)
peer.consumerCh <- RPC{
Command: args,
Reader: r,
RespChan: respCh,
}
// Wait for a response
select {
case rpcResp = <-respCh:
if rpcResp.Error != nil {
err = rpcResp.Error
}
case <-time.After(timeout):
err = fmt.Errorf("command timed out")
}
return
}
示例15: newNetAddress
// newNetAddress attempts to extract the IP address and port from the passed
// net.Addr interface and create a bitcoin NetAddress structure using that
// information.
func newNetAddress(addr net.Addr, services btcwire.ServiceFlag) (*btcwire.NetAddress, error) {
// addr will be a net.TCPAddr when not using a proxy.
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
ip := tcpAddr.IP
port := uint16(tcpAddr.Port)
na := btcwire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// addr will be a socks.ProxiedAddr when using a proxy.
if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok {
ip := net.ParseIP(proxiedAddr.Host)
if ip == nil {
ip = net.ParseIP("0.0.0.0")
}
port := uint16(proxiedAddr.Port)
na := btcwire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// For the most part, addr should be one of the two above cases, but
// to be safe, fall back to trying to parse the information from the
// address string as a last resort.
host, portStr, err := net.SplitHostPort(addr.String())
if err != nil {
return nil, err
}
ip := net.ParseIP(host)
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
}
na := btcwire.NewNetAddressIPPort(ip, uint16(port), services)
return na, nil
}