| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "flag" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "net" |
| 8 | ) |
| 9 | |
| 10 | func main() { |
| 11 | target := flag.String("target", "", "the server address") |
| 12 | payload := flag.String("message", "", "the message to send to the server") |
| 13 | protocol := flag.String("protocol", "tcp", "the protocol to use with the server [udp,tcp], default tcp") |
| 14 | flag.Parse() |
| 15 | |
| 16 | if *target == "" || *payload == "" { |
| 17 | flag.Usage() |
| 18 | panic("invalid arguments") |
| 19 | } |
| 20 | |
| 21 | switch *protocol { |
| 22 | case "tcp": |
| 23 | connectTCP(*target, *payload) |
| 24 | case "udp": |
| 25 | connectUDP(*target, *payload) |
| 26 | default: |
| 27 | panic("invalid protocol") |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func connectTCP(target, payload string) { |
| 32 | conn, err := net.Dial("tcp", target) |
| 33 | if err != nil { |
| 34 | panic(fmt.Sprintf("Failed to open connection to [%s] %v", target, err)) |
| 35 | } |
| 36 | defer conn.Close() |
| 37 | |
| 38 | _, err = conn.Write([]byte(payload)) |
| 39 | if err != nil { |
| 40 | panic("Failed to send payload") |
| 41 | } |
| 42 | _, err = conn.Write([]byte("\n")) |
| 43 | if err != nil { |
| 44 | panic("Failed to send payload") |
| 45 | } |
| 46 | buf := make([]byte, 1024) |
| 47 | for { |
| 48 | n, err := conn.Read(buf) |
| 49 | fmt.Print(string(buf[:n])) |
| 50 | if err == io.EOF { |
| 51 | break |
| 52 | } |
| 53 | if err != nil { |
| 54 | panic("Failed to read from socket") |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // UDP uses a constant source port to trigger conntrack problems |
| 60 | func connectUDP(target, payload string) { |
| 61 | LocalAddr, err := net.ResolveUDPAddr("udp", ":54321") |
| 62 | if err != nil { |
| 63 | panic(fmt.Sprintf("Failed to resolve UDP local address on port 54321 %v", err)) |
| 64 | } |
| 65 | RemoteAddr, err := net.ResolveUDPAddr("udp", target) |
| 66 | if err != nil { |
| 67 | panic(fmt.Sprintf("Failed to resolve UDP remote address [%s] %v", target, err)) |
| 68 | } |
| 69 | conn, err := net.DialUDP("udp", LocalAddr, RemoteAddr) |
| 70 | if err != nil { |
| 71 | panic(fmt.Sprintf("Failed to open connection to [%s] %v", target, err)) |
| 72 | } |
| 73 | defer conn.Close() |
| 74 | |
| 75 | _, err = conn.Write([]byte(payload)) |
| 76 | if err != nil { |
| 77 | panic("Failed to send payload") |
| 78 | } |
| 79 | _, err = conn.Write([]byte("\n")) |
| 80 | if err != nil { |
| 81 | panic("Failed to send payload") |
| 82 | } |
| 83 | |
| 84 | buf := make([]byte, 1024) |
| 85 | n, err := conn.Read(buf) |
| 86 | if err != nil { |
| 87 | panic("Failed to read from socket") |
| 88 | } |
| 89 | fmt.Print(string(buf[:n])) |
| 90 | } |