Created
December 3, 2020 09:28
-
-
Save majek/0aaf03fc74c18d64ccaf6eb072c317c7 to your computer and use it in GitHub Desktop.
echo server in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"net" | |
"os" | |
"strings" | |
) | |
var quiet *bool | |
func main() { | |
port := flag.Int("port", 0, "port to run on") | |
addr := flag.String("addr", "", "addr to run on") | |
quiet = flag.Bool("quiet", false, "Surpress logs") | |
flag.Parse() | |
var as string | |
if !strings.Contains(*addr, ":") { | |
as = fmt.Sprintf("%s:%d", *addr, *port) | |
} else { | |
as = fmt.Sprintf("[%s]:%d", *addr, *port) | |
} | |
tcpAddr, err := net.ResolveTCPAddr("tcp", as) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[!] resolve failed: %s\n", err) | |
os.Exit(-1) | |
} | |
tcpLn, err := net.ListenTCP("tcp", tcpAddr) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[!] couldn't start listening: %s\n", err) | |
os.Exit(-1) | |
} | |
lnAddr := tcpLn.Addr() | |
tcpAddr = lnAddr.(*net.TCPAddr) | |
if *port == 0 { | |
fmt.Printf("%d\n", tcpAddr.Port) | |
} | |
udpAddr, err := net.ResolveUDPAddr("udp", tcpAddr.String()) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[!] resolve failed: %s\n", err) | |
os.Exit(-1) | |
} | |
udpLn, err := net.ListenUDP("udp", udpAddr) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[!] couldn't start listening: %s\n", err) | |
os.Exit(-1) | |
} | |
go runTCPEcho(tcpLn) | |
runUDPEcho(udpLn) | |
} | |
func runUDPEcho(ln *net.UDPConn) { | |
var ( | |
pos int | |
arr = make([]string, 10, 10) | |
) | |
var buf [4096]byte | |
for { | |
n, raddr, err := ln.ReadFromUDP(buf[:]) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "[-] read failed: %s\n", err) | |
continue | |
} | |
ln.WriteToUDP([]byte(fmt.Sprintf("%d\n", n)), raddr) | |
m := fmt.Sprintf("udp://%s\n", raddr.String()) | |
for _, v := range arr { | |
if v == m { | |
m = "" | |
break | |
} | |
} | |
if m != "" { | |
arr[pos] = m | |
pos = (pos + 1) % len(arr) | |
if *quiet == false { | |
fmt.Printf("%s", m) | |
} | |
} | |
} | |
} | |
func runTCPEcho(ln *net.TCPListener) { | |
for { | |
conn, err := ln.Accept() | |
if conn == nil { | |
fmt.Fprintf(os.Stderr, "[-] accept failed: %s\n", err) | |
continue | |
} | |
if *quiet == false { | |
fmt.Printf("tcp://%s\n", conn.RemoteAddr()) | |
} | |
go handleTCP(conn) | |
} | |
} | |
func handleTCP(conn net.Conn) { | |
var buf [4096]byte | |
for { | |
n, err := conn.Read(buf[:]) | |
if err != nil { | |
break | |
} | |
_, err = conn.Write(buf[:n]) | |
if err != nil { | |
break | |
} | |
} | |
conn.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment