arnaucube
arnaucube/goDDOSPublic Self-hosted repository
one simple connection client-server sending strings, works
arnaucode idoctnef@openmailbox.org
Wed, 15 Mar 2017 18:27:09 +0100
commit

aa94b72ec1b4193b01381eed2d49f5b98c018a12

parent

44f7a86b1cfbcd3dc36b025a6a04350315e31c60

2 files changed, 114 insertions(+), 0 deletions(-)

jump to
A client/main.go

@@ -0,0 +1,59 @@

+package main + +import ( + "bufio" + "fmt" + "net" + "os" +) + +func main() { //client https://systembash.com/a-simple-go-tcp-server-and-tcp-client/ + + // connect to this socket + conn, _ := net.Dial("tcp", "127.0.0.1:3333") + hostname, err := os.Hostname() + if err != nil { + fmt.Println(err) + os.Exit(1) + } + fmt.Println("connecting to server as hostname:", hostname) + ip := getIp() + fmt.Println("local ip:", ip) + // send to socket + fmt.Fprintf(conn, hostname+", ip: "+ip.String()+"\n") + for { + message, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + fmt.Println(err) + fmt.Println("server disconnected") + os.Exit(1) + } + fmt.Print("Command from server: " + message) + } + +} + +func getIp() net.IP { + var ip net.IP + ifaces, err := net.Interfaces() + if err != nil { + fmt.Println(err) + } + for _, i := range ifaces { + addrs, err := i.Addrs() + if err != nil { + fmt.Println(err) + } + for _, addr := range addrs { + + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + // process IP address + } + } + return ip +}
A server/main.go

@@ -0,0 +1,55 @@

+package main + +import ( + "bufio" + "fmt" + "net" + "os" +) + +const ( + CONN_HOST = "localhost" + CONN_PORT = "3333" + CONN_TYPE = "tcp" +) + +func main() { //server + + fmt.Println("Launching server...") + + // listen on all interfaces + ln, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT) + if err != nil { + fmt.Println("Error listening:", err.Error()) + os.Exit(1) + } + + // Close the listener when the application closes. + defer ln.Close() + defer fmt.Println("ended") + + fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT) + + // accept connection on port + c, err := ln.Accept() + if err != nil { + fmt.Println("Error accepting: ", err.Error()) + os.Exit(1) + } + // will listen for message to process ending in newline (\n) + message, _ := bufio.NewReader(c).ReadString('\n') + // output message received + fmt.Print("client connected:", string(message), "\n") + for { + /*// will listen for message to process ending in newline (\n) + message, _ := bufio.NewReader(c).ReadString('\n') + // output message received + fmt.Print("client connected:", string(message), "\n")*/ + + newcommand := bufio.NewReader(os.Stdin) + fmt.Print("command to send to the clients: ") + text, _ := newcommand.ReadString('\n') + // send new string back to client + c.Write([]byte(text + "\n")) + } +}