-
Notifications
You must be signed in to change notification settings - Fork 0
/
goroute.go
213 lines (178 loc) · 4.54 KB
/
goroute.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"sync"
"time"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
)
type Result struct {
IP string
HOP int
TimeElapsedMS float64
}
func createICMPPacket(id int, seq int) []byte {
// Create a new ICMP message
m := icmp.Message{
Type: ipv4.ICMPTypeEcho, Code: 0,
Body: &icmp.Echo{
ID: id, Seq: seq,
Data: []byte("GO-ROUTE"),
},
}
// Marshal the message
b, err := m.Marshal(nil)
if err != nil {
log.Fatal(err)
}
return b
}
func waitResponses(c *icmp.PacketConn, timeout time.Duration,
startTime float64, targetHost string, maxTTL int, id int, wg *sync.WaitGroup) {
// create a new Timer
timer := time.NewTimer(timeout)
// create a channel to receive the results
results := make(map[int]Result, 0)
// reply buffer
reply := make([]byte, 1500)
go func() {
for {
// Read the response
n, peer, err := c.ReadFrom(reply)
if err != nil {
break
}
// Parse the response
rm, err := icmp.ParseMessage(1, reply[:n])
if err != nil {
log.Println("failed to parse ICMPv4 message: ", err)
break
}
// check type of ICMP message
switch rm.Type {
case ipv4.ICMPTypeEchoReply:
t, ok := rm.Body.(*icmp.Echo)
if !ok {
log.Println("not an echo reply")
break
}
// we skip if the response does not
// come from the target host
if peer.String() != targetHost {
continue
}
// store results in a map keyed by the sequence number
r := Result{
IP: peer.String(),
HOP: t.Seq,
TimeElapsedMS: float64(time.Now().UnixNano()/1000000) - startTime,
}
// store the result
results[t.Seq] = r
// if we've received an echo reply from targetHost
// we can signal we are done
// done <- struct{}{}
// return
case ipv4.ICMPTypeTimeExceeded:
// cast to icmp.TimeExceeded
t, ok := rm.Body.(*icmp.TimeExceeded)
if !ok {
log.Println("failed to cast to icmp.TimeExceeded")
break
}
// icmp.TimeExceeded contains the original packet
// so we grab IPv4 header and ICMP header
ipHdr, err := icmp.ParseIPv4Header(t.Data)
if err != nil {
log.Println("failed to parse IPv4 header", err)
break
}
// grab the ICMP header
if icmpMsg, err := icmp.ParseMessage(1, t.Data[ipHdr.Len:]); err == nil {
if msg, ok := icmpMsg.Body.(*icmp.Echo); ok && msg.ID == id {
r := Result{
IP: peer.String(),
HOP: msg.Seq,
TimeElapsedMS: float64(time.Now().UnixNano()/1000000) - startTime,
}
results[msg.Seq] = r
}
} else {
log.Println("failed to parse inner ICMPv4 message", err)
}
default:
log.Printf("Unexpected response %+v: %s", rm, peer.String())
}
}
}()
// wait for the timer to expire
<-timer.C
// print the results
for i := 1; i <= maxTTL; i++ {
if r, ok := results[i]; ok {
fmt.Printf("%d\t%s\t%.2f ms\n", r.HOP, r.IP, r.TimeElapsedMS)
if r.IP == targetHost {
break
}
} else {
fmt.Printf("%d\t*\n", i)
}
}
wg.Done()
}
var (
host = flag.String("host", "", "host to traceroute")
maxHops = flag.Int("max-hops", 30, "max hops")
timeout = flag.Duration("timeout", 2*time.Second, "timeout")
probes = flag.Int("probes", 3, "number of probes per hop")
)
func main() {
flag.Parse()
// check host is not empty
if *host == "" {
flag.Usage()
os.Exit(1)
}
// start listening for ICMP messages
c, err := icmp.ListenPacket("ip4:icmp", "")
if err != nil {
log.Fatal(err)
}
defer c.Close()
id := os.Getpid() & 0xffff
remoteHost, err := net.ResolveIPAddr("ip4", *host)
if err != nil {
log.Fatal(err)
}
// create a wait group to wait for all the goroutines to finish
wg := &sync.WaitGroup{}
// output message
fmt.Printf("traceroute to %s (%s), %d hops max, timeout %s, start time %s\n",
*host, remoteHost.String(), *maxHops, *timeout, time.Now().Format(time.RFC3339))
// start time in milliseconds
startTime := float64(time.Now().UnixNano()) / 1000000
wg.Add(1)
go waitResponses(c, *timeout,
startTime, remoteHost.IP.String(), *maxHops, id, wg)
for ttl := 1; ttl <= *maxHops; ttl++ {
// Set the TTL
if err := c.IPv4PacketConn().SetTTL(ttl); err != nil {
log.Println("failed to set TTL: ", err)
continue
}
// send N probes for each message
for i := 0; i < *probes; i++ {
// Create an ICMP packet
b := createICMPPacket(id, ttl)
// Send the packet
if _, err := c.WriteTo(b, remoteHost); err != nil {
log.Println("failed to write packet: ", err)
}
}
}
wg.Wait()
}