-
Notifications
You must be signed in to change notification settings - Fork 127
/
nat_test.go
79 lines (67 loc) · 1.5 KB
/
nat_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
//
// date : 2016-05-13
// author: xjdrew
//
package kone
import (
"math/rand"
"net"
"testing"
"time"
)
func TestNatAlloc(t *testing.T) {
var from uint16 = 10
var to uint16 = 20
nat := NewNat(from, to)
srcIP := net.ParseIP("127.0.0.1")
dstIP := srcIP
// map all ports
for i := from; i < to; i++ {
_, port := nat.allocSession(srcIP, dstIP, i, i)
if i != port {
t.Error("alloc session failed")
return
}
}
// release all sessions
now := time.Now().Unix() + NatSessionLifeSeconds
nat.clearExpiredSessions(now)
if nat.count() != 0 {
t.Error("release session failed")
return
}
// test get session
srcPort := uint16(rand.Int())
dstPort := uint16(rand.Int())
_, port := nat.allocSession(srcIP, dstIP, srcPort, dstPort)
session := nat.getSession(port)
if session == nil {
t.Error("get session failed")
return
}
if !net.IP.Equal(session.srcIP, srcIP) || !net.IP.Equal(session.dstIP, dstIP) ||
session.srcPort != srcPort || session.dstPort != dstPort {
t.Error("check session failed")
return
}
}
func BenchmarkNat(b *testing.B) {
var from uint16 = 10000
var to uint16 = 60000
nat := NewNat(from, to)
srcIP := net.ParseIP("127.0.0.1")
dstIP := srcIP
// map all ports
for i := from; i < to; i++ {
_, port := nat.allocSession(srcIP, dstIP, i, i)
if i != port {
b.Error("alloc session failed")
}
}
// release all sessions
now := time.Now().Unix() + NatSessionLifeSeconds
nat.clearExpiredSessions(now)
if nat.count() != 0 {
b.Error("release session failed")
}
}