90 lines
1.6 KiB
Go
90 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"flag"
|
|
"log"
|
|
"net"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var PortOutOfRange = errors.New("Port out of allowed range 1-65535")
|
|
var isDebug bool
|
|
|
|
func init() {
|
|
isDebug = false
|
|
}
|
|
|
|
func debug(v ...interface{}) {
|
|
if isDebug {
|
|
msg := make([]interface{}, len(v)+1)
|
|
msg[0] = "[DEBUG]"
|
|
for i, el := range v {
|
|
msg[i+1] = el
|
|
}
|
|
log.Println(msg...)
|
|
}
|
|
}
|
|
|
|
func handleConn(c net.Conn) {
|
|
defer c.Close()
|
|
debug("connection established:", c)
|
|
reader := bufio.NewReader(c)
|
|
|
|
for {
|
|
data, err := reader.ReadString('\n')
|
|
debug("Data =>", data)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
cleanData := strings.TrimSpace(string(data))
|
|
duration, err := time.ParseDuration(cleanData)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
debug("Duration =>", duration)
|
|
c.Write([]byte("ACK\n"))
|
|
time.Sleep(duration)
|
|
}
|
|
|
|
log.Println("connection closed:", c)
|
|
}
|
|
|
|
func parsePort(port int) (string, error) {
|
|
if port < 1 || port > 65535 {
|
|
return "", PortOutOfRange
|
|
}
|
|
return strconv.Itoa(port), nil
|
|
}
|
|
|
|
func main() {
|
|
var address string
|
|
var port int
|
|
flag.StringVar(&address, "addr", "", "The target address or ip")
|
|
flag.IntVar(&port, "port", 0, "The target port")
|
|
flag.BoolVar(&isDebug, "debug", false, "Enable debug logging")
|
|
flag.Parse()
|
|
|
|
parsedPort, err := parsePort(port)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
host := net.JoinHostPort(address, parsedPort)
|
|
server, err := net.Listen("tcp4", host)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer server.Close()
|
|
|
|
for {
|
|
c, err := server.Accept()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
go handleConn(c)
|
|
}
|
|
}
|