Advertisement
The_Defalt

netcat_sock.go

Dec 8th, 2018
538
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.31 KB | None | 0 0
  1. package main
  2.  
  3. // This is a simple program that will connect to a listening netcat server, send a hello, and receive a reply
  4. // This is meant as an example of client-side socket usage
  5.  
  6. import (
  7.     "fmt"
  8.     "net"
  9.     "bufio"
  10.     "os"
  11.     "time"
  12.     "strings"
  13. )
  14.  
  15. // IP addr and port number to connect to
  16. var address string = "127.0.0.1:4444" // CHANGE THIS
  17.  
  18. // dial server and return connection object
  19. func dialServer() net.Conn {
  20.     conn, err := net.Dial("tcp", address)
  21.     if err != nil {
  22.         fmt.Printf("Fatal error: %s", err)
  23.         os.Exit(3)
  24.     }
  25.     return conn
  26. }
  27.  
  28. func main() {
  29.     // call dialServer
  30.     fmt.Printf("[*] Connecting to server... ")
  31.     conn := dialServer()
  32.     fmt.Println("[DONE]")
  33.     time.Sleep(3 * time.Second)
  34.  
  35.     // send hello message to netcat server
  36.     fmt.Printf("[*] Sending hello to server... ")
  37.     fmt.Fprintf(conn, "Hello, Netcat!\n")
  38.     fmt.Println("[DONE]")
  39.     time.Sleep(3 * time.Second)
  40.  
  41.     // receive reply from netcat
  42.     fmt.Printf("[*] Receiving reply from server... ")
  43.     reply, err := bufio.NewReader(conn).ReadString('\n')
  44.     if err != nil {
  45.         fmt.Println("[FAIL]")
  46.         os.Exit(3)
  47.     }
  48.     reply = strings.TrimSpace(reply) // trim leading whitespace and newline
  49.     fmt.Printf("[RECEIVED: %s]\n", reply)
  50.     conn.Close()
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement