本文整理汇总了Golang中net.UDPConn.LocalAddr方法的典型用法代码示例。如果您正苦于以下问题:Golang UDPConn.LocalAddr方法的具体用法?Golang UDPConn.LocalAddr怎么用?Golang UDPConn.LocalAddr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.UDPConn
的用法示例。
在下文中一共展示了UDPConn.LocalAddr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: DialTunnel
func DialTunnel(addr string) (tc net.Conn, err error) {
var conn *net.UDPConn
var t *Tunnel
udpaddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return
}
conn, err = net.DialUDP("udp", nil, udpaddr)
if err != nil {
return
}
localaddr := conn.LocalAddr()
localstr := localaddr.String()
name := fmt.Sprintf("%s_cli", strings.Split(localstr, ":")[1])
t = NewTunnel(udpaddr, name, make(chan *SendBlock, TBUFSIZE))
c := &Client{t, conn, name, make(chan uint8)}
t.onclose = func() {
sutils.Info("close tunnel", localaddr)
conn.Close()
close(c.c_close)
close(t.c_send)
}
go c.sender()
go c.recver()
t.c_event <- EV_CONNECT
<-t.c_connect
sutils.Info("create tunnel", localaddr)
return &TunnelConn{t, localaddr}, nil
}
示例2: listen
func (udp *Udp) listen(conn *net.UDPConn) {
log.Info("Begin listening for UDP on address %s", conn.LocalAddr())
buffer := make([]byte, c_BUFSIZE)
for {
num, _, err := conn.ReadFromUDP(buffer)
if err != nil {
if udp.stop {
log.Info("Stopped listening for UDP on %s", conn.LocalAddr)
break
} else {
log.Severe("Failed to read from UDP buffer: " + err.Error())
continue
}
}
pkt := append([]byte(nil), buffer[:num]...)
go func() {
msg, err := parser.ParseMessage(pkt)
if err != nil {
log.Warn("Failed to parse SIP message: %s", err.Error())
} else {
udp.output <- msg
}
}()
}
}
示例3: GatherCandidates
func GatherCandidates(sock *net.UDPConn) ([]candidate, error) {
laddr := sock.LocalAddr().(*net.UDPAddr)
ret := []candidate{}
switch {
case laddr.IP.IsLoopback():
return nil, errors.New("Connecting over loopback not supported")
case laddr.IP.IsUnspecified():
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip, ok := addr.(*net.IPNet)
if ok && ip.IP.IsGlobalUnicast() {
ret = append(ret, candidate{&net.UDPAddr{ip.IP, laddr.Port, ""}, 0})
}
}
default:
ret = append(ret, candidate{laddr, 0})
}
// Get the reflexive address
reflexive, err := getReflexive(sock)
if err == nil {
ret = append(ret, candidate{reflexive, 0})
}
setPriorities(ret)
return ret, nil
}
示例4: newUDPSession
func (listener *Listener) newUDPSession(remote *net.UDPAddr) (*UDPSession, bool) {
remoteAddrStr := remote.String()
listener.Lock()
if sess, ok := listener.remoteAddrs[remoteAddrStr]; ok == true {
listener.Unlock()
return sess, true
}
listener.Unlock()
var err error
var local *net.UDPConn
if local, err = net.ListenUDP("udp", &net.UDPAddr{}); err != nil {
//log.Println(err)
return nil, false
}
localAddr := local.LocalAddr().(*net.UDPAddr)
sess := newUDPSession(listener, remote, local, localAddr)
listener.Lock()
listener.remoteAddrs[remoteAddrStr] = sess
listener.Unlock()
return sess, false
}
示例5: GetClientId
// Creates a 2 byte ClientID from the local machine's IP.
func GetClientId() (id []byte, err error) {
var conn *net.UDPConn
var addr *net.UDPAddr
// Connect to a random machine somewhere in this subnet. It's irrelevant
// where to, as long as it's not the loopback address.
if addr, err = net.ResolveUDPAddr("udp", "192.168.1.1:0"); err != nil {
return
}
if conn, err = net.DialUDP("udp", nil, addr); err != nil {
return
}
defer conn.Close()
// strip port number off.
str := conn.LocalAddr().String()
if idx := strings.LastIndex(str, ":"); idx != -1 {
str = str[0:idx]
}
var ip net.IP
if ip = net.ParseIP(str).To16(); ip == nil {
return
}
// TODO(jimt): I am unsure how 2 full IPv6 addresses in the same subnet relate
// to eachother. Specifically if the 2 last bytes in the 16-byte address are
// really the relevant bits that set them apart from eachother.
// For IPv4 this is simple: 192.168.2.101 vs 192.168.2.102 -> we need the
// '2.101' and '2.102' bits. Bytes are stored in Big Endian order.
id = []byte{ip[14], ip[15]}
return
}
示例6: udpConnectionReader
/*
Used to listen for incoming UDP packets on an given connection. Runs an infinite loop reading from the connection to a buffer.
When a message is complete, it sends it to to the caller via the receive channel.
*/
func udpConnectionReader(connection *net.UDPConn, messageSize int, receiveChannel chan<- UDPMessage) {
defer func() {
if r := recover(); r != nil {
log.Println("UDPConnectionReader:\t ERROR in udpConnectionReader:\t %s \n Closig connection.", r)
connection.Close()
}
}()
for {
if debug {
log.Printf("UDPConnectionReader:\t Waiting on data from UDPConnection %s\n", connection.LocalAddr().String())
}
buffer := make([]byte, messageSize) // TODO: Do without allocation memory each time!
n, returnAddress, err := connection.ReadFromUDP(buffer)
if err != nil || n < 0 || n > messageSize {
log.Println("UDPConnectionReader:\t Error in ReadFromUDP:", err)
} else {
if debug {
log.Println("UDPConnectionReader:\t Received package from:", returnAddress.String())
log.Println("UDP-Listen:\t", string(buffer[:]))
}
receiveChannel <- UDPMessage{RAddress: returnAddress.String(), Data: buffer[:n], Length: n}
}
}
}
示例7: listenServer
func listenServer(conn *net.UDPConn, receiveChannel chan UDPMessage, networkLogger log.Logger) {
networkLogger.Printf("Listening on %s", conn.LocalAddr().String())
for {
buf := make([]byte, 1024)
len, raddr, _ := conn.ReadFromUDP(buf)
receiveChannel <- UDPMessage{Address: IP(raddr.IP.String()), Data: buf[:len], Length: len}
}
}
示例8: getUDPAddr
func getUDPAddr(conn *net.UDPConn) *net.UDPAddr {
addr := conn.LocalAddr()
udpAddr, ok := addr.(*net.UDPAddr)
if !ok {
log.Fatal()
}
return udpAddr
}
示例9: Listen
// Listen launches the various server goroutines and starts the various listeners.
// If the listener params are nil, these are constructed from the parameters in the conf. Otherwise they are
// used as-is. This makes it possible for the tests to construct listeners on an available port and pass them
// in.
func (s *Server) Listen(clientConn *net.UDPConn, forwardListener, debugListener net.Listener) error {
go s.handleMetaStats()
go s.flush()
go s.aggregate()
if s.conf.OSStats != nil {
go s.checkOSStats()
}
if s.conf.Scripts != nil {
go s.runScripts()
}
if s.conf.forwardingEnabled {
s.forwardingIncoming = make(chan *Stat, incomingQueueSize)
go s.flushForwarding()
go s.aggregateForwarding()
}
errorCh := make(chan error)
if s.conf.forwarderEnabled {
if forwardListener == nil {
l, err := net.Listen("tcp", s.conf.ForwarderListenAddr)
if err != nil {
return err
}
forwardListener = tcpKeepAliveListener{l.(*net.TCPListener)}
}
s.l.Println("Listening for forwarded gost messages on", forwardListener.Addr())
go s.aggregateForwarded()
go func() {
errorCh <- s.forwardServer(forwardListener)
}()
}
if err := s.debugServer.Start(s.conf.DebugPort, debugListener); err != nil {
return err
}
if clientConn == nil {
udpAddr := fmt.Sprintf("localhost:%d", s.conf.Port)
udp, err := net.ResolveUDPAddr("udp", udpAddr)
if err != nil {
return err
}
clientConn, err = net.ListenUDP("udp", udp)
if err != nil {
return err
}
}
s.l.Println("Listening for UDP client requests on", clientConn.LocalAddr())
go func() {
errorCh <- s.clientServer(clientConn)
}()
// Indicate that we've started
s.metaInc("server_start")
return <-errorCh
}
示例10: handleudp
func handleudp(conn *net.UDPConn, remaddr net.Addr, message []byte) {
fmt.Printf("UDP packet from %s (to %s)... ", remaddr, conn.LocalAddr())
n, error := conn.WriteTo(message, remaddr)
checkError("Cannot write", error)
if n != len(message) {
panic("Cannot write")
}
fmt.Printf("Echoed %d bytes\n", n)
}
示例11: GatherCandidates
func GatherCandidates(sock *net.UDPConn, outIpList string) ([]candidate, error) {
laddr := sock.LocalAddr().(*net.UDPAddr)
ret := []candidate{}
switch {
case laddr.IP.IsLoopback():
return nil, errors.New("Connecting over loopback not supported")
case laddr.IP.IsUnspecified():
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip, ok := addr.(*net.IPNet)
if ok && ip.IP.IsGlobalUnicast() {
ret = append(ret, candidate{&net.UDPAddr{IP: ip.IP, Port: laddr.Port}})
}
}
default:
ret = append(ret, candidate{laddr})
}
addip := func(ipStr string, port int) {
ip := net.ParseIP(ipStr)
if port == 0 {
port = laddr.Port
}
bHave := false
for _, info := range ret {
if info.Addr.IP.Equal(ip) && info.Addr.Port == port {
bHave = true
break
}
}
if !bHave {
ret = append(ret, candidate{&net.UDPAddr{IP: ip, Port: port}})
}
}
// Get the reflexive address
if *stunserver != "" {
ip, port, err := getReflexive(sock)
if err == nil {
addip(ip, port)
}
}
arr := strings.Split(outIpList, ";")
for _, ip := range arr {
addip(ip, 0)
}
/* for _, info := range ret {
log.Println("init ip:", info.Addr.String())
}*/
return ret, nil
}
示例12: findAddress
func findAddress() (addr string, err error) {
var udpAddr *net.UDPAddr
if udpAddr, err = net.ResolveUDPAddr("udp", "www.internic.net:80"); err != nil {
return
}
var udpConn *net.UDPConn
if udpConn, err = net.DialUDP("udp", nil, udpAddr); err != nil {
return
}
addr = udpConn.LocalAddr().String()
return
}
示例13: StartListener
func StartListener(conn *net.UDPConn, callback func(address *net.UDPAddr)) {
log.Println("listener:Listening on:", conn.LocalAddr())
buf := make([]byte, 1024)
for {
//log.Println("listener:going to read")
n, addr, err := conn.ReadFromUDP(buf)
checkError(err)
log.Println("listener:received:", n, "bytes from:", addr)
callback(addr)
}
}
示例14: listen
func listen(c chan string, conn *net.UDPConn, label string) {
log.Printf("listening to %s", conn.LocalAddr().String())
buf := make([]byte, 9999)
for {
n, _, err := conn.ReadFromUDP(buf)
if err != nil {
log.Print(err)
time.Sleep(3 * time.Second)
continue
}
s := string(buf[:n])
log.Printf("%s got {%s}", label, s)
c <- s
}
}
示例15: TestIngestPacket_CRC
func TestIngestPacket_CRC(t *testing.T) {
m := GetMemberlist(t)
m.config.EnableCompression = false
defer m.Shutdown()
var udp *net.UDPConn
for port := 60000; port < 61000; port++ {
udpAddr := fmt.Sprintf("127.0.0.1:%d", port)
udpLn, err := net.ListenPacket("udp", udpAddr)
if err == nil {
udp = udpLn.(*net.UDPConn)
break
}
}
if udp == nil {
t.Fatalf("no udp listener")
}
// Get a message with a checksum
payload := []byte{3, 3, 3, 3}
m.rawSendMsgUDP(udp.LocalAddr(), &Node{PMax: 5}, payload)
in := make([]byte, 1500)
n, _, err := udp.ReadFrom(in)
if err != nil {
t.Fatalf("unexpected err %s", err)
}
in = in[0:n]
if len(in) != 9 {
t.Fatalf("bad: %v", in)
}
// Corrupt the checksum
in[1] <<= 1
logs := &bytes.Buffer{}
logger := log.New(logs, "", 0)
m.logger = logger
m.ingestPacket(in, udp.LocalAddr(), time.Now())
if !strings.Contains(logs.String(), "invalid checksum") {
t.Fatalf("bad: %s", logs.String())
}
}