-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.go
99 lines (84 loc) · 1.83 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 (
"fmt"
"log"
"os"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"github.com/urfave/cli"
)
var (
snapshot_len int32 = 1024
promiscuous bool = false
err error
timeout time.Duration = 100 * time.Millisecond
handle *pcap.Handle
)
func findDevice(c *cli.Context) string {
if c.String("interface") != "" {
return c.String("interface")
}
devices, err := pcap.FindAllDevs()
if err != nil {
panic(err)
}
return devices[0].Name
}
func createHandle(c *cli.Context) (*pcap.Handle, error) {
fileName := c.String("read")
if fileName != "" {
return pcap.OpenOffline(fileName)
} else {
device := findDevice(c)
return pcap.OpenLive(device, snapshot_len, promiscuous, timeout)
}
}
func findSource(c *cli.Context) (*gopacket.PacketSource, func()) {
handle, err := createHandle(c)
if err != nil {
log.Fatal(err)
}
if c.String("filter") != "" {
err := handle.SetBPFFilter(c.String("filter"))
if err != nil {
log.Fatal(err)
}
}
return gopacket.NewPacketSource(handle, handle.LinkType()), handle.Close
}
func main() {
app := cli.NewApp()
app.Name = "tcpterm"
app.Usage = "tcpdump for human"
app.Version = "0.0.1"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "interface, i",
Usage: "If unspecified, use lowest numbered interface.",
},
cli.StringFlag{
Name: "read, r",
Usage: "Read packets from pcap file.",
},
cli.StringFlag{
Name: "filter, f",
Usage: "BPF Filter",
},
cli.BoolFlag{
Name: "debug",
Usage: "debug mode.",
},
}
app.Action = func(c *cli.Context) error {
packetSource, close := findSource(c)
defer close()
tcpterm := NewTcpterm(packetSource, c.Bool("debug"))
tcpterm.Run()
return nil
}
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}