本文整理汇总了Golang中net.PacketConn.LocalAddr方法的典型用法代码示例。如果您正苦于以下问题:Golang PacketConn.LocalAddr方法的具体用法?Golang PacketConn.LocalAddr怎么用?Golang PacketConn.LocalAddr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.PacketConn
的用法示例。
在下文中一共展示了PacketConn.LocalAddr方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: test1
func test1(conn net.PacketConn, addr net.Addr, softwareName string) (*packet, net.Addr, bool, *Host, error) {
packet, err := sendBindingReq(conn, addr, softwareName)
if err != nil {
return nil, nil, false, nil, err
}
if packet == nil {
return nil, nil, false, nil, nil
}
// RFC 3489 doesn't require the server return XOR mapped address.
hostMappedAddr := packet.xorMappedAddr()
if hostMappedAddr == nil {
hostMappedAddr = packet.mappedAddr()
if hostMappedAddr == nil {
return nil, nil, false, nil, errors.New("No mapped address.")
}
}
identical := isLocalAddress(conn.LocalAddr().String(), hostMappedAddr.TransportAddr())
hostChangedAddr := packet.changedAddr()
if hostChangedAddr == nil {
return packet, nil, identical, hostMappedAddr, nil
}
changedAddrStr := hostChangedAddr.TransportAddr()
changedAddr, err := net.ResolveUDPAddr("udp", changedAddrStr)
if err != nil {
return nil, nil, false, nil, errors.New("Failed to resolve changed address.")
}
return packet, changedAddr, identical, hostMappedAddr, nil
}
示例2: newConnection
func newConnection(c net.PacketConn, addr net.Addr, tq *timerQueue, tag []byte, closed func()) *connection {
conn := &connection{
Cond: sync.Cond{L: new(sync.Mutex)},
addr: addr,
localAddr: c.LocalAddr(),
closeWait: make(chan struct{}),
}
var tag3 [3]byte
copy(tag3[:], tag)
go conn.proc(c, tq, tag3, closed)
return conn
}
示例3: Serve
// Serve accepts incoming TFTP read requests on the listener l,
// creating a new service goroutine for each. The service goroutines
// use handler to get a byte stream and send it to the client.
func Serve(l net.PacketConn, handler Handler) {
Log("Listening on %s", l.LocalAddr())
buf := make([]byte, 512)
for {
n, addr, err := l.ReadFrom(buf)
if err != nil {
Log("Reading from socket: %s", err)
continue
}
req, err := parseRRQ(addr, buf[:n])
if err != nil {
Debug("parseRRQ: %s", err)
l.WriteTo(mkError(err), addr)
continue
}
go transfer(addr, req, handler)
}
}
示例4: start
func (self *UdpServer) start() error {
var conn net.PacketConn
var e error
if nil == self.listenAddr {
conn, e = net.ListenPacket("udp", self.origin)
} else {
conn, e = net.ListenPacket("udp", self.listenAddr.String())
}
if nil != e {
return e
}
self.conn = conn
self.listenAddr = conn.LocalAddr()
self.waitGroup.Add(1)
go self.serve()
return nil
}
示例5: Start
func (svr *snmpTestServer) Start() {
var in net.PacketConn
var e error
if nil == svr.listenAddr {
in, e = net.ListenPacket("udp", svr.origin)
svr.t.Log("[test_server]", "listen at", in.LocalAddr())
} else {
in, e = net.ListenPacket("udp", svr.listenAddr.String())
svr.t.Log("[test_server]", "listen at", svr.listenAddr.String())
}
if nil != e {
panic(e.Error())
}
svr.isFirstListen = false
svr.waitGroup.Add(1)
svr.conn = in
svr.listenAddr = in.LocalAddr()
go serveTestUdp2(svr)
}
示例6: ListenConn
// Listen announces on existing packet-based connection
func ListenConn(conn net.PacketConn) (net.Listener, error) {
l := &listener{
Cond: sync.Cond{
L: new(sync.Mutex),
},
addr: conn.LocalAddr(),
}
rld := &receiveLoopData{
Cond: sync.Cond{
L: new(sync.Mutex),
},
buffers: [][]byte{
make([]byte, 65536),
make([]byte, 65536),
make([]byte, 65536),
},
}
pld := &processLoopData{
Cond: sync.Cond{
L: new(sync.Mutex),
},
}
l.stopListening = func() {
pld.L.Lock()
pld.rejectNewConnections = true
pld.L.Unlock()
pld.Signal()
}
go receiveLoop(conn, l, rld, pld)
go processLoop(conn, l, rld, pld)
return l, nil
}
示例7:
logMessages []*events.LogMessage
udpConn net.PacketConn
)
var _ = Describe("LogIntegration", func() {
Context("with standard initialization", func() {
origin := []string{"test-origin"}
BeforeEach(func() {
var err error
logMessages = nil
udpConn, err = net.ListenPacket("udp4", ":0")
Expect(err).ToNot(HaveOccurred())
go listenForLogs()
udpAddr := udpConn.LocalAddr().(*net.UDPAddr)
dropsonde.Initialize(fmt.Sprintf("localhost:%d", udpAddr.Port), origin...)
sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter())
batcher := metricbatcher.New(sender, 100*time.Millisecond)
metrics.Initialize(sender, batcher)
})
AfterEach(func() {
udpConn.Close()
})
It("sends dropped error message for messages which are just under 64k and don't fit in UDP packet", func() {
logSender := log_sender.NewLogSender(dropsonde.AutowiredEmitter(), time.Second, loggertesthelper.Logger())
const length = 64*1024 - 1
reader := strings.NewReader(strings.Repeat("s", length) + "\n")
示例8:
})
})
Describe("Emit()", func() {
var udpEmitter emitter.ByteEmitter
Context("when the agent is listening", func() {
var agentListener net.PacketConn
BeforeEach(func() {
var err error
agentListener, err = net.ListenPacket("udp4", "")
Expect(err).ToNot(HaveOccurred())
udpEmitter, err = emitter.NewUdpEmitter(agentListener.LocalAddr().String())
Expect(err).ToNot(HaveOccurred())
})
AfterEach(func() {
agentListener.Close()
})
It("should send the data", func(done Done) {
err := udpEmitter.Emit(testData)
Expect(err).ToNot(HaveOccurred())
buffer := make([]byte, 4096)
readCount, _, err := agentListener.ReadFrom(buffer)
Expect(err).ToNot(HaveOccurred())
Expect(buffer[:readCount]).To(Equal(testData))
示例9:
for {
buffer := make([]byte, 1024)
n, _, err := testMetricsListener.ReadFrom(buffer)
if err != nil {
close(testMetricsChan)
return
}
var envelope events.Envelope
err = proto.Unmarshal(buffer[:n], &envelope)
Expect(err).NotTo(HaveOccurred())
testMetricsChan <- &envelope
}
}()
port, err := strconv.Atoi(strings.TrimPrefix(testMetricsListener.LocalAddr().String(), "127.0.0.1:"))
Expect(err).NotTo(HaveOccurred())
client = bbs.NewClient(bbsURL.String())
bbsArgs = testrunner.Args{
Address: bbsAddress,
AdvertiseURL: bbsURL.String(),
AuctioneerAddress: auctioneerServer.URL(),
ConsulCluster: consulRunner.ConsulCluster(),
DropsondePort: port,
EtcdCluster: etcdUrl, // etcd is still being used to test version migration in migration_version_test.go
DatabaseDriver: sqlRunner.DriverName(),
DatabaseConnectionString: sqlRunner.ConnectionString(),
MetricsReportInterval: 10 * time.Millisecond,
HealthAddress: bbsHealthAddress,
示例10: processLoop
// receives packets from the receive loop and dispatches them
// to their corresponding connections
func processLoop(c net.PacketConn, l *listener, rld *receiveLoopData, pld *processLoopData) {
var (
quit bool
wg = new(sync.WaitGroup)
tq = newTimerQueue()
connections = struct {
sync.RWMutex
M map[uint32]*connection
}{
M: make(map[uint32]*connection),
}
)
// keep a refcount to `c` for ourselves
wg.Add(1)
defer wg.Done()
// wait for all pending connections, then close the socket
go func() {
wg.Wait()
c.Close()
tq.Close()
}()
// generate a new key for cookies
cookieKey := make([]byte, sha1.Size)
if _, err := crand.Read(cookieKey); err != nil {
l.L.Lock()
l.err = fmt.Errorf("Failed to generate cookie secret: %v", err)
l.L.Unlock()
l.Broadcast()
return
}
sig := hmac.New(sha1.New, cookieKey)
// generate addler32(localaddr)
var localAddrSum [4]byte
binary.LittleEndian.PutUint32(localAddrSum[:], adler32.Checksum([]byte(c.LocalAddr().String())))
shouldWait := func() bool {
waitOnConnections := pld.rejectNewConnections && pld.remainingConnections == 0
return pld.err == nil && len(pld.Q) == 0 && !waitOnConnections
}
var packets []processLoopPacket
for !quit {
// wait for a packet to become available
pld.L.Lock()
for shouldWait() {
pld.Wait()
}
rejectNewConnections := pld.rejectNewConnections
pldErr := pld.err
quit = pldErr != nil
packets, pld.Q = pld.Q, packets[:0]
remainingConnections := pld.remainingConnections
pld.L.Unlock()
if rejectNewConnections && remainingConnections == 0 {
quit = true
}
// process packets
for ii := range packets {
buffer, addr := packets[ii].D, packets[ii].A
switch PacketType(buffer[0]) {
case PacketInit:
// are we accepting new connections?
if rejectNewConnections {
continue
}
// verify length
const MinInitPacketLength = 9
if len(buffer) < MinInitPacketLength {
continue
}
// verify protocol magic
if !bytes.Equal(buffer[1:5], protocolMagic) {
continue
}
// verify version
if buffer[5] != version1 {
sendAbort(c, addr, buffer[6:9])
continue
}
var outgoing [32]byte
now := time.Now()
outgoing[0] = byte(PacketCookie)
if _, err := crand.Read(outgoing[1:4]); err != nil {
return
//.........这里部分代码省略.........