func (self *UdpInput) Init(config interface{}) error { self.config = config.(*UdpInputConfig) if len(self.config.Address) > 3 && self.config.Address[:3] == "fd:" { // File descriptor fdStr := self.config.Address[3:] fdInt, err := strconv.ParseUint(fdStr, 0, 0) if err != nil { log.Println(err) return fmt.Errorf("Invalid file descriptor: %s", self.config.Address) } fd := uintptr(fdInt) udpFile := os.NewFile(fd, "udpFile") self.listener, err = net.FileConn(udpFile) if err != nil { return fmt.Errorf("Error accessing UDP fd: %s\n", err.Error()) } } else { // IP address udpAddr, err := net.ResolveUDPAddr("udp", self.config.Address) if err != nil { return fmt.Errorf("ResolveUDPAddr failed: %s\n", err.Error()) } self.listener, err = net.ListenUDP("udp", udpAddr) if err != nil { return fmt.Errorf("ListenUDP failed: %s\n", err.Error()) } } return nil }
func udpInit(localListenPort, broadcastListenPort, messageSize int, sendCh, receiveCh chan udpMessage) (err error) { //Generating broadcast address baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(broadcastListenPort)) if err != nil { return err } //Generating localaddress tempConn, err := net.DialUDP("udp4", nil, baddr) defer tempConn.Close() tempAddr := tempConn.LocalAddr() laddr, err := net.ResolveUDPAddr("udp4", tempAddr.String()) laddr.Port = localListenPort def.LocalIP = laddr.String() //Creating local listening connections localListenConn, err := net.ListenUDP("udp4", laddr) if err != nil { return err } //Creating listener on broadcast connection broadcastListenConn, err := net.ListenUDP("udp", baddr) if err != nil { localListenConn.Close() return err } udpConnection = true go udpReceiveServer(localListenConn, broadcastListenConn, messageSize, receiveCh) go udpTransmitServer(localListenConn, broadcastListenConn, sendCh) return err }
func main() { //测试手动注册两个通道 sip.GetChannel("10.2.42.197", "10.2.42.133") sip.GetChannel("10.2.42.133", "10.2.42.197") //链接WebRTC 服务 go webrtcSocket.Init() //开启出测地址 go sip.InitListener() //监听视频端口 service := ":8088" udpAddr, err := net.ResolveUDPAddr("udp", service) checkError(err) conn, err := net.ListenUDP("udp", udpAddr) checkError(err) fmt.Println("监听端口") for { handleVideo(conn) } //监听语音端口 go func() { serviceAudio := ":11113" udpAddrAudio, err := net.ResolveUDPAddr("udp", serviceAudio) checkError(err) connAudio, err := net.ListenUDP("udp", udpAddrAudio) checkError(err) for { handleAudio(connAudio) } }() }
func ListenAndServe(addr string, port int) { //addr_tcp, err := net.ResolveTCPAddr("tcp", l) //if err != nil { // panic(err) //} //listen_tcp, err := net.ListenTCP("tcp", addr_tcp) //if err != nil { // panic(err) //} //go tcp_listen(listen_tcp) rtp_l := fmt.Sprintf("%v:%v", addr, port) rtcp_l := fmt.Sprintf("%v:%v", addr, port+1) addr1, err := net.ResolveUDPAddr("udp", rtp_l) if err != nil { panic(err) } listen_rtp, err := net.ListenUDP("udp", addr1) if err != nil { panic(err) } go udp_rtp_listen(listen_rtp) addr2, err := net.ResolveUDPAddr("udp", rtcp_l) if err != nil { panic(err) } listen_rtcp, err := net.ListenUDP("udp", addr2) if err != nil { panic(err) } go udp_rtcp_listen(listen_rtcp) }
func Udp_init(localListenPort, broadcastListenPort, message_size int, send_ch, receive_ch chan Udp_message) (err error) { //Generating broadcast address baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(broadcastListenPort)) if err != nil { return err } //Generating localaddress tempConn, err := net.DialUDP("udp4", nil, baddr) defer tempConn.Close() tempAddr := tempConn.LocalAddr() laddr, err = net.ResolveUDPAddr("udp4", tempAddr.String()) laddr.Port = localListenPort //Creating local listening connections localListenConn, err := net.ListenUDP("udp4", laddr) if err != nil { return err } //Creating listener on broadcast connection broadcastListenConn, err := net.ListenUDP("udp", baddr) if err != nil { localListenConn.Close() return err } go udp_receive_server(localListenConn, broadcastListenConn, message_size, receive_ch) go udp_transmit_server(localListenConn, broadcastListenConn, send_ch) // fmt.Printf("Generating local address: \t Network(): %s \t String(): %s \n", laddr.Network(), laddr.String()) // fmt.Printf("Generating broadcast address: \t Network(): %s \t String(): %s \n", baddr.Network(), baddr.String()) return err }
func Test_ContextCloseFuncWithConn(t *testing.T) { time.Sleep(1 * time.Second) testResult := make(chan error) conns := make([]*net.UDPConn, 3) for x := 0; x < 3; x++ { a := net.UDPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 12345 + x, } c, err := net.ListenUDP("udp", &a) if err != nil { t.Fatal(err.Error()) } conns[x] = c } ctx := NewContextWithConn(conns) // Test done channel testTimeout := time.After(200 * time.Millisecond) go func() { select { case <-testTimeout: errMsg := "Expect to close done channel" testResult <- errors.New(errMsg) case <-ctx.DoneChan: testResult <- nil } }() ctx.Done() // Test if a connection not closed for x := 0; x < 3; x++ { a := net.UDPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 12345 + x, } c, err := net.ListenUDP("udp", &a) if err != nil { t.Fatal(err.Error()) } err = c.Close() if err != nil { t.Fatal(err.Error()) } } err := <-testResult if err != nil { t.Fatal(err.Error()) } time.Sleep(1 * time.Second) }
func initSockets(BROADCAST_IP string, PORTNUM_COST string, PORTNUM_ORDER string) bool { //Create broadcast socket for orders broadcast_udp_addr, err := net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_ORDER) if err != nil { log.Println(" ResolveUDPAddr failed", err) } broadcast_order_conn, err := net.DialUDP("udp", nil, broadcast_udp_addr) if err != nil { log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err) return false } broadcast_order_conn = broadcast_order_conn //Create broadcast socket for cost updates broadcast_udp_addr, err = net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_COST) if err != nil { log.Println("ResolveUDPAddr failed", err) } broadcast_cost_conn, err = net.DialUDP("udp", nil, broadcast_udp_addr) if err != nil { log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err) return false } broadcast_cost_conn = broadcast_cost_conn //Create receiver socket for external orders listen_addr, err := net.ResolveUDPAddr("udp", PORTNUM_ORDER) if err != nil { log.Println("ResolveUDPAddr failed ", err) } receive_order_conn, err := net.ListenUDP("udp", listen_addr) if err != nil { log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err) return false } receive_order_conn = receive_order_conn //Create receiver socket for cost updates listen_addr, err = net.ResolveUDPAddr("udp", PORTNUM_COST) if err != nil { log.Println("ResolveUDPAddr failed ", err) } receive_cost_conn, err := net.ListenUDP("udp", listen_addr) if err != nil { log.Println("Could not establish UDP connection. Enter single eleveator mode.\n", err) return false } receive_cost_conn = receive_cost_conn return true }
func Dial(remote string) (*UDPSession, error) { // defer SavePanic() //log.Println("Dial") remoteAddr, err := net.ResolveUDPAddr("udp", remote) if err != nil { return nil, err } tmpSock, _err := net.ListenUDP("udp", nil) if _err != nil { return nil, _err } // 必须新建一个 否则服务端新socket发送过来的数据 会直接被丢弃 接收不到 localSock, _err := net.ListenUDP("udp", nil) if _err != nil { return nil, _err } localAddr := localSock.LocalAddr().(*net.UDPAddr) //buf := make([]byte, 1500) //udp包大小不超过1400 wbuf := make([]byte, 5) buf := make([]byte, 5) wbuf[0] = CmdCreateSession binary.LittleEndian.PutUint32(wbuf[1:], uint32(localAddr.Port)) for j := 0; j < 20; j = j + 1 { tmpSock.WriteTo(wbuf, remoteAddr) tmpSock.SetReadDeadline(time.Now().Add(300 * time.Millisecond)) n, from, err := tmpSock.ReadFromUDP(buf) if n >= len(buf) && from.String() == remoteAddr.String() { if buf[0] == CmdCreateSessionRsp { //log.Println("CmdCreateSessionRsp") tmpSock.Close() newAddr := net.UDPAddr{ IP: from.IP, Port: int(binary.LittleEndian.Uint32(buf[1:])), } session := newUDPSession(nil, &newAddr, localSock, localAddr) go session.readLoop() go session.updateLoop() return session, nil } } if n < 0 { //log.Println("dial: n < 0 ") tmpSock.Close() localSock.Close() return nil, err } } tmpSock.Close() localSock.Close() return nil, errors.New("dial: no response") }
/* This function initializes the UDP module. It sets the port for listening, broadcasting, the approved message size and the channels for communicating with the calling module. It returns the local IP-address of this system/module, and an error if if it fails(then ip is ""). */ func Init(localListenPort, broadcastListenPort, messageSize int, sendChannel <-chan UDPMessage, receiveChannel chan<- UDPMessage) (localIP string, err error) { // Generate broadcast address broadcastAdress, err = net.ResolveUDPAddr(udp4, broadcastIp+strconv.Itoa(broadcastListenPort)) if err != nil { log.Println("UDP:\t Could not resolve UDPAddress.") return "", err } else if debug { // We are in debug mode. log.Printf("UDP:\t Generating broadcast address:\t %s \n", broadcastAdress.String()) } // Generate local address, uses the tempConnection to fetch address via the UDP dial. tempConnection, err := net.DialUDP(udp4, nil, broadcastAdress) if err != nil { log.Println("UDP:\t No network connection") return "", err } defer tempConnection.Close() // Makes sure the connection is closed when Init completes. tempAddress := tempConnection.LocalAddr() localAddress, err = net.ResolveUDPAddr(udp4, tempAddress.String()) if err != nil { log.Println("UDP:\t Could not resolve local address.") return "", err } else if debug { log.Printf("UDP:\t Generating local address: \t%s \n", localAddress.String()) } localAddress.Port = localListenPort // Set the port property of the *net.UDPAddr struct // Create local listening connections localListenConnection, err := net.ListenUDP(udp4, localAddress) // Listens for incoming UDP packets addressed to localAddress. if err != nil { log.Println("UDP:\t Couldn't create a UDP listener socket.") return "", err } if debug { log.Println("UDP:\t Created a UDP listener socket.") } // Create a listener on broadcast connection. broadcastListenConnection, err := net.ListenUDP(udp4, &net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: broadcastListenPort}) if err != nil { log.Println("UDP:\t Could not create a UDP broadcast listen socket.") localListenConnection.Close() return "", err } if debug { log.Println("UDP:\t Created a UDP broadcast listen socket.") } // Start goroutines to handle incoming messages and sending outgoing messages. go udpReceiveServer(localListenConnection, broadcastListenConnection, messageSize, receiveChannel) go udpTransmitServer(localListenConnection, broadcastListenConnection, localListenPort, broadcastListenPort, sendChannel) return localAddress.IP.String(), err }
func TestSecureUdp(t *testing.T) { data := []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff} port := ":0" udpAddr, err := net.ResolveUDPAddr("udp", port) if err != nil { t.Fatal(err) } ln, err := net.ListenUDP("udp", udpAddr) if err != nil { t.Fatal(err) } Addr := ln.LocalAddr() defer ln.Close() cipher, err := NewCipher("aes-256-cfb", "password") if err != nil { t.Fatal(err) } go func() { secureConn := NewPacketConn(ln, cipher.Copy()) buf := make([]byte, 1500) n, src, err := secureConn.ReadFrom(buf) if err != nil { t.Fatal(err) } if !bytes.Equal(buf[:n], data) { t.Error("UDP server recieved data does not match.") } _, err = secureConn.WriteTo(buf[:n], src) if err != nil { t.Fatal(err) } return }() time.Sleep(100 * time.Millisecond) ln2, err := net.ListenUDP("udp", udpAddr) if err != nil { t.Fatal(err) } secureconn := NewPacketConn(ln2, cipher.Copy()) _, err = secureconn.WriteTo(data, Addr) if err != nil { t.Fatal(err) } buf := make([]byte, 1500) n, _, err := secureconn.ReadFrom(buf) if err != nil { t.Fatal(err) } if !bytes.Equal(buf[:n], data) { t.Error("UDP client read does not match.") } }
// Constructs server structure func newServer(iface *net.Interface) (*Server, error) { // Create wildcard connections (because :5353 can be already taken by other apps) ipv4conn, err := net.ListenUDP("udp4", mdnsWildcardAddrIPv4) if err != nil { log.Printf("[ERR] bonjour: Failed to bind to udp4 port: %v", err) } ipv6conn, err := net.ListenUDP("udp6", mdnsWildcardAddrIPv6) if err != nil { log.Printf("[ERR] bonjour: Failed to bind to udp6 port: %v", err) } if ipv4conn == nil && ipv6conn == nil { return nil, fmt.Errorf("[ERR] bonjour: Failed to bind to any udp port!") } // Join multicast groups to receive announcements p1 := ipv4.NewPacketConn(ipv4conn) p2 := ipv6.NewPacketConn(ipv6conn) if iface != nil { if err := p1.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil { return nil, err } if err := p2.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil { return nil, err } } else { ifaces, err := net.Interfaces() if err != nil { return nil, err } errCount1, errCount2 := 0, 0 for _, iface := range ifaces { if err := p1.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil { errCount1++ } if err := p2.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil { errCount2++ } } if len(ifaces) == errCount1 && len(ifaces) == errCount2 { return nil, fmt.Errorf("Failed to join multicast group on all interfaces!") } } s := &Server{ ipv4conn: ipv4conn, ipv6conn: ipv6conn, ttl: 3200, } return s, nil }
// Client structure constructor func newClient(iface *net.Interface, serviceChan chan<- *ServiceEntry) (*client, error) { // Create wildcard connections (because :5353 can be already taken by other apps) ipv4conn, err := net.ListenUDP("udp4", mdnsWildcardAddrIPv4) if err != nil { log.Printf("[ERR] bonjour: Failed to bind to udp4 port: %v", err) } ipv6conn, err := net.ListenUDP("udp6", mdnsWildcardAddrIPv6) if ipv4conn == nil && ipv6conn == nil { return nil, fmt.Errorf("[ERR] bonjour: Failed to bind to any udp port!") } // Join multicast groups to receive announcements from server p1 := ipv4.NewPacketConn(ipv4conn) p2 := ipv6.NewPacketConn(ipv6conn) if iface != nil { if err := p1.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil { return nil, err } if err := p2.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil { return nil, err } } else { ifaces, err := net.Interfaces() if err != nil { return nil, err } errCount1, errCount2 := 0, 0 for _, iface := range ifaces { if err := p1.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil { errCount1++ } if err := p2.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil { errCount2++ } } if len(ifaces) == errCount1 && len(ifaces) == errCount2 { return nil, fmt.Errorf("Failed to join multicast group on all interfaces!") } } c := &client{ lookupParams: make(map[string]*LookupParams), serviceChan: serviceChan, ipv4conn: ipv4conn, ipv6conn: ipv6conn, closedCh: make(chan bool), } return c, nil }
// ListenOnTransports listens for incoming RTP and RTCP packets addressed // to this transport. // func (tp *TransportUDP) ListenOnTransports() (err error) { tp.dataConn, err = net.ListenUDP(tp.localAddrRtp.Network(), tp.localAddrRtp) if err != nil { return } tp.ctrlConn, err = net.ListenUDP(tp.localAddrRtcp.Network(), tp.localAddrRtcp) if err != nil { tp.dataConn.Close() tp.dataConn = nil return } go tp.readDataPacket() go tp.readCtrlPacket() return nil }
func InitSendService(speed int64, from string, to string) (service *SendService, err error) { service = new(SendService) service.speed = speed addr, err := net.ResolveUDPAddr("udp4", from) if err != nil { return nil, err } service.addr, err = net.ResolveUDPAddr("udp4", to) if err != nil { return nil, err } service.conn, err = net.ListenUDP("udp4", addr) if err != nil { return nil, err } // conn, err := net.Dial("udp", "127.0.0.1:12345") // if err != nil { // panic(err) // } // service.conn = conn return service, nil }
func NewDiscoverer(id string, port int, extPort int, extServer string) (*Discoverer, error) { local4 := &net.UDPAddr{IP: net.IP{0, 0, 0, 0}, Port: AnnouncementPort} conn, err := net.ListenUDP("udp4", local4) if err != nil { return nil, err } disc := &Discoverer{ MyID: id, ListenPort: port, BroadcastIntv: 30 * time.Second, ExtListenPort: extPort, ExtBroadcastIntv: 1800 * time.Second, conn: conn, registry: make(map[string]string), extServer: extServer, } go disc.recvAnnouncements() if disc.ListenPort > 0 { disc.sendAnnouncements() } if len(disc.extServer) > 0 && disc.ExtListenPort > 0 { disc.sendExtAnnouncements() } return disc, nil }
// Listen creates a UDP server that parses statsd data into metrics and // sends them over a channel. func Listen(addr string, c chan Packet, clean bool) { cleaner := NewCleaner() laddr, err := net.ResolveUDPAddr("udp", addr) if err != nil { log.Fatalln("fatal: failed to resolve address", err) } conn, err := net.ListenUDP("udp", laddr) if err != nil { log.Fatalln("fatal: failed to listen", err) } for { buf := make([]byte, 1452) n, raddr, err := conn.ReadFrom(buf[:]) t := time.Now().UTC() if err != nil { log.Println("error: Failed to recieve packet", err) } else { metrics, err := Parse(buf[0:n]) if err != nil { log.Println("error: Failed to recieve packet", err) } if metrics != nil { var p Packet if clean { cleaned := cleaner.CleanMetrics(*metrics) p = Packet{&cleaned, raddr, t} } else { p = Packet{metrics, raddr, t} } c <- p } } } }
// Open a udp connection on addr, and loop input in a goroutine func (s *Server) listen(addr string) error { udpAddr, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } s.conn, err = net.ListenUDP("udp", udpAddr) if err != nil { return err } // loop reading go func() { for { buff := make([]byte, 1024) n, addr, err := s.conn.ReadFromUDP(buff) if s.open { *s.in <- Packet{buff, n, addr, err} } else { close(*s.in) return } } }() return nil }
func main() { flag.Parse() go gResolver(*dnsname, *ttl) laddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("%s:%d", *bindaddr, *inport)) if err != nil { log.Printf("Cannot resolve %s:%d: %s", *bindaddr, *inport, err) return } conn, err := net.ListenUDP("udp4", laddr) if err != nil { log.Printf("Cannot listen on %s: %s", laddr, err) return } for { b := make([]byte, 1500) _, _, _, raddr, err := conn.ReadMsgUDP(b, nil) if err != nil { log.Printf("error reading udp message: %s", err) return } log.Printf("got packet from: %s", raddr) go gHandleUdpPacket(b) } }
func ExampleV9Decoder() { // Boiler plate UDP server addr, _ := net.ResolveUDPAddr("udp", ":2055") server, _ := net.ListenUDP("udp", addr) // This is our decoder decoder := NewDecoder() // Shared cache for all decoders and sources cache := make(V9TemplateCache) // Forever receive messages from the network for { var msg = make([]byte, 8192) if _, _, err := server.ReadFromUDP(msg); err == nil { if d, err := decoder.Decode(msg); err != nil { if v9, ok := d.(*V9Decoder); ok { v9.Cache = cache } // Now use d.Next() or feed trough d.Flows() } } } }
func (r *resolver) SetupFunc(port int) func() { return (func() { var err error // DNS operates primarily on UDP addr := &net.UDPAddr{ IP: net.ParseIP(r.listenAddress), Port: port, } r.conn, err = net.ListenUDP("udp", addr) if err != nil { r.err = fmt.Errorf("error in opening name server socket %v", err) return } // Listen on a TCP as well tcpaddr := &net.TCPAddr{ IP: net.ParseIP(r.listenAddress), Port: port, } r.tcpListen, err = net.ListenTCP("tcp", tcpaddr) if err != nil { r.err = fmt.Errorf("error in opening name TCP server socket %v", err) return } r.err = nil }) }
// Listener receives packets from the udp buffer, parses them and feeds both the Metrics channel // as well as the metricAmounts channel func Listener(listen_addr, prefix_internal string, output *common.Output, parse parseLineFunc) { address, err := net.ResolveUDPAddr("udp", listen_addr) if err != nil { log.Fatalf("ERROR: Cannot resolve '%s' - %s", listen_addr, err) } listener, err := net.ListenUDP("udp", address) if err != nil { log.Fatalf("ERROR: ListenUDP - %s", err) } defer listener.Close() log.Printf("listening on %s", address) message := make([]byte, MaxUdpPacketSize) for { n, remaddr, err := listener.ReadFromUDP(message) if err != nil { log.Printf("ERROR: reading UDP packet from %+v - %s", remaddr, err) continue } for _, p := range ParseMessage(message[:n], prefix_internal, output, parse) { output.Metrics <- p output.MetricAmounts <- common.MetricAmount{p.Bucket, p.Sampling} } } }
func main() { udpAddr, err := net.ResolveUDPAddr("udp", ":20014") if err != nil { log.Fatal(err) } udpListen, err := net.ListenUDP("udp", udpAddr) if err != nil { log.Fatal(err) } backupvalue := backup(udpListen) fmt.Println(backupvalue) udpListen.Close() udpAddr, err = net.ResolveUDPAddr("udp", "129.241.187.255:20014") if err != nil { log.Fatal(err) } udpBroadcast, err := net.DialUDP("udp", nil, udpAddr) if err != nil { log.Fatal(err) } primary(backupvalue, udpBroadcast) udpBroadcast.Close() }
//----------------------------------------------- Stats Server start func main() { defer func() { if x := recover(); x != nil { log.Println("caught panic in main()", x) } }() config := cfg.Get() // start logger if config["stats_log"] != "" { cfg.StartLogger(config["stats_log"]) } log.Println("Starting Stats Server") go SignalProc() go SysRoutine() // Listen service := DEFAULT_SERVICE if config["stats_service"] != "" { service = config["stats_service"] } log.Println("Stats Service:", service) udpAddr, err := net.ResolveUDPAddr("udp", service) checkError(err) udpconn, err := net.ListenUDP("udp", udpAddr) checkError(err) log.Println("Stats Server OK.") handleClient(udpconn) }
func listenImAlive() { service := broadcast + ":" + UDPport addr, err := net.ResolveUDPAddr("udp4", service) if err != nil { fmt.Println("net.ResolveUDPAddr error in listenImAlive: ", err) internal.setupFail <- true } isalivesocket, err := net.ListenUDP("udp4", addr) if err != nil { fmt.Println("net.ListenUDP error in listenImAlive: ", err) internal.setupFail <- true } var data [512]byte for { select { case <-internal.quitlistenImAlive: return default: _, senderAddr, err := isalivesocket.ReadFromUDP(data[0:]) if err != nil { fmt.Println("ReadFromUDP error in listenImAlive: ", err) } if localIP != senderAddr.IP.String() { if err != nil { fmt.Println("read error in listenImAlive") } else { remoteElev := senderAddr.IP.String() internal.isAlivechan <- remoteElev } } } } }
func TestMetricSink(t *testing.T) { udpAddr, err := net.ResolveUDPAddr("udp", DogStatsdAddr) if err != nil { t.Fatal(err) } server, err := net.ListenUDP("udp", udpAddr) if err != nil { t.Fatal(err) } defer server.Close() buf := make([]byte, 1024) for _, tt := range MetricSinkTests { dog := MockNewDogStatsdSink(DogStatsdAddr, tt.Tags, tt.PropagateHostname) method := reflect.ValueOf(dog).MethodByName(tt.Method) method.Call([]reflect.Value{ reflect.ValueOf(tt.Metric), reflect.ValueOf(tt.Value)}) n, _ := server.Read(buf) msg := buf[:n] if string(msg) != tt.Expected { t.Fatalf("Line %s does not match expected: %s", string(msg), tt.Expected) } } }
func (g *statsdUdpTextServiceManager) Start(file *os.File) error { var ( err error udpAddr *net.UDPAddr ) if config.StatsdUdpListenSpec != "" { if file != nil { g.conn, err = net.FileConn(file) } else { udpAddr, err = net.ResolveUDPAddr("udp", config.StatsdUdpListenSpec) if err == nil { g.conn, err = net.ListenUDP("udp", udpAddr) } } } else { log.Printf("Not starting Statsd UDP protocol because statsd-udp-listen-spec is blank.") return nil } if err != nil { return fmt.Errorf("Error starting Statsd UDP Text Protocol serviceManager: %v", err) } fmt.Printf("Statsd UDP protocol Listening on %s\n", config.StatsdTextListenSpec) // for UDP timeout must be 0 go handleStatsdTextProtocol(g.t, g.conn, 0) return nil }
func (s *Server) ListenAndServe() error { uaddr, err := net.ResolveUDPAddr("udp", s.Addr) if err != nil { return err } conn, err := net.ListenUDP("udp", uaddr) if err != nil { return err } defer conn.Close() log.Println("listening on", uaddr) newmsg := make(chan Message) go messageReceiver(s, newmsg) for { b := make([]byte, 1024) n, addr, err := conn.ReadFrom(b) if err != nil { log.Println("error %v", err) continue } heartbeat := Message{From: addr.String()} b = bytes.TrimLeft(b[:n], "\n") heartbeat.extract(b) // remove newline newmsg <- heartbeat } }
func (this *SyslogProducer) startUDPServer() { Trace(this, "Starting UDP server") udpAddr, err := net.ResolveUDPAddr("udp", this.config.UDPAddr) if err != nil { panic(err) } connection, err := net.ListenUDP("udp", udpAddr) if err != nil { panic(err) } closeChannel := make(chan bool, 1) this.closeChannels = append(this.closeChannels, closeChannel) go func() { for { select { case <-closeChannel: return default: } this.scan(connection) } }() Infof(this, "Listening for messages at UDP %s", this.config.UDPAddr) }
func main() { theCache = cache.New(time.Hour, time.Minute) var err error server, err = net.ResolveUDPAddr("udp", "208.67.220.220:53") if err != nil { fmt.Fprintf(os.Stderr, "Can't resolve server address: %v\n", err) os.Exit(1) } addr, err := net.ResolveUDPAddr("udp", "0.0.0.0:53") if err != nil { fmt.Fprintf(os.Stderr, "Can't resolve service address: %v\n", err) os.Exit(1) } conn, err := net.ListenUDP("udp", addr) if err != nil { fmt.Fprintf(os.Stderr, "Can't listen on udp port: %v\n", err) os.Exit(1) } replyCh = make(chan *reply) go sendReply(conn) for { reqData := make([]byte, 2048) nr, client, err := conn.ReadFromUDP(reqData) if err != nil { fmt.Fprintf(os.Stderr, "Failed to read from client: %v\n", err) //checkTempErr(err) continue } go proxyClientDNS(reqData[:nr], client) } }
// udpListen starts listening for udp packets on the configured port. func (s *Statsd) udpListen() error { address, _ := net.ResolveUDPAddr("udp", s.ServiceAddress) listener, err := net.ListenUDP("udp", address) if err != nil { log.Fatalf("ERROR: ListenUDP - %s", err) } defer listener.Close() log.Println("Statsd listener listening on: ", listener.LocalAddr().String()) for { select { case <-s.done: return nil default: buf := make([]byte, 1024) n, _, err := listener.ReadFromUDP(buf) if err != nil { log.Printf("ERROR: %s\n", err.Error()) } lines := strings.Split(string(buf[:n]), "\n") for _, line := range lines { line = strings.TrimSpace(line) if line != "" { select { case s.in <- line: default: log.Printf(dropwarn, line) } } } } } }