forked from songgao/water
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ipv4_test.go
81 lines (70 loc) · 1.55 KB
/
ipv4_test.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
package water
import (
"net"
"os/exec"
"testing"
"time"
"github.com/songgao/water/waterutil"
)
const BUFFERSIZE = 1522
func startRead(ch chan<- []byte, ifce *Interface) {
go func() {
for {
buffer := make([]byte, BUFFERSIZE)
_, err := ifce.Read(buffer)
if err == nil {
ch <- buffer
}
}
}()
}
func startBroadcast(t *testing.T, dst net.IP) {
if err := exec.Command("ping", "-b", "-c", "2", dst.String()).Start(); err != nil {
t.Fatal(err)
}
}
func TestBroadcast(t *testing.T) {
var (
self = net.IPv4(10, 0, 42, 1)
mask = net.IPv4Mask(255, 255, 255, 0)
brd = net.IPv4(10, 0, 42, 255)
)
ifce, err := NewTAP("test")
if err != nil {
t.Fatal(err)
}
setupIfce(t, net.IPNet{IP: self, Mask: mask}, ifce.Name())
startBroadcast(t, brd)
dataCh := make(chan []byte, 8)
startRead(dataCh, ifce)
timeout := time.NewTimer(8 * time.Second).C
readFrame:
for {
select {
case buffer := <-dataCh:
ethertype := waterutil.MACEthertype(buffer)
if ethertype != waterutil.IPv4 {
continue readFrame
}
if !waterutil.IsBroadcast(waterutil.MACDestination(buffer)) {
continue readFrame
}
packet := waterutil.MACPayload(buffer)
if !waterutil.IsIPv4(packet) {
continue readFrame
}
if !waterutil.IPv4Source(packet).Equal(self) {
continue readFrame
}
if !waterutil.IPv4Destination(packet).Equal(brd) {
continue readFrame
}
if waterutil.IPv4Protocol(packet) != waterutil.ICMP {
continue readFrame
}
break readFrame
case <-timeout:
t.Fatal("Waiting for broadcast packet timeout")
}
}
}