Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PING server using Go
// Start using
// go run ping.go -addr=:3141
// Query using
// nc -u localhost 3141
package main
import (
"log"
"net"
"flag"
"bytes"
)
func main() {
addr := flag.String("addr", "localhost:0", "addr")
flag.Parse()
// resolve address
ServerAddr, err := net.ResolveUDPAddr("udp", *addr)
if err != nil {
log.Fatal("Couldn't resolve passed in addr ", err)
}
// start listening
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil {
log.Fatal("Couldn't listen on passed in addr " , err)
}
log.Println("Listening on", ServerConn.LocalAddr().String())
// close connection as soon as program exists
defer ServerConn.Close()
// used for incoming messages
buf := make([]byte, 1024)
PING := []byte("PING\n")
PONG := []byte("PONG\n")
for {
n, addr, err := ServerConn.ReadFromUDP(buf)
log.Println("Received ", string(buf[0:n]), " from ", addr)
if err != nil {
log.Println("Error: ", err)
}
if bytes.Equal(buf[:len(PING)], PING) {
ServerConn.WriteTo(PONG, addr)
continue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment