-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
99 lines (83 loc) · 1.73 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"flag"
"fmt"
"github.com/RyanJarv/little-stitch/lib"
"io"
"log"
"os"
"strconv"
"strings"
)
func help() {
log.Fatalf("USAGE: %s <server|client>\n", os.Args[0])
}
func main() {
flag.Parse()
if len(flag.Args()) < 1 {
help()
}
if flag.Args()[0] == "client" {
client(flag.Args()[1:]...)
} else if (len(os.Args) >= 1) && (flag.Args()[0] == "server") {
server()
} else {
help()
}
}
func server() {
server, err := lib.NewServer()
if err != nil {
log.Fatalf("starting server: %s\n", err)
}
go func() {
_, err = io.Copy(server.Send, os.Stdin)
if err != nil {
log.Fatalf("error writing to send pipe: %s\n", err)
}
err := server.Send.Close()
if err != nil {
fmt.Printf("failed to close send pipe: %s\n", err)
}
}()
_, err = io.Copy(os.Stdout, server.Recieve)
if err != nil {
log.Fatalf("error copying to stdout: %s\n", err)
}
}
func client(args ...string) {
if len(args) != 1 {
log.Fatalf("USAGE: %s client <ip>\n", os.Args[0])
}
ip := parseIp(args[0])
client := lib.NewClient(ip)
go func() {
_, err := io.Copy(client.Send, os.Stdin)
if err != nil {
log.Fatalf("error writing to send pipe: %s\n", err)
}
err = client.Send.Close()
if err != nil {
fmt.Printf("error closing send pipe: %s\n", err)
}
}()
_, err := io.Copy(os.Stdout, client.Receive)
if err != nil {
fmt.Printf("error copying to stdout: %s\n", err)
}
}
func parseIp(s string) []byte {
ip := make([]byte, 4)
split := strings.Split(s, ".")
if len(split) != 4 {
log.Fatalf("USAGE: %s client <ip>\n", os.Args[0])
}
for i := 0; i < 4; i++ {
d, err := strconv.Atoi(split[i])
if err != nil {
fmt.Printf("failed to parse ip address: %s\n", err)
}
ip[i] = byte(d)
}
return ip
}