1
0
mirror of https://github.com/taigrr/go-fastping synced 2025-01-18 05:03:15 -08:00

Fixed payload size. Added tests.

This commit is contained in:
Simon Whitehead 2014-11-06 08:28:54 +11:00 committed by Tatsushi Demachi
parent 1a8c22e90d
commit 56843b1f9f
2 changed files with 26 additions and 7 deletions

View File

@ -47,12 +47,9 @@ import (
"time" "time"
) )
const TimeSliceLengh = 8 const TimeSliceLength = 8
func byteSliceOfSize(n int) []byte { func byteSliceOfSize(n int) []byte {
if n == 0 {
n = TimeSliceLengh // if its 0 .. default it to 8
}
b := make([]byte, n) b := make([]byte, n)
for i := 0; i < len(b); i++ { for i := 0; i < len(b); i++ {
b[i] = 1 b[i] = 1
@ -139,7 +136,7 @@ func NewPinger() *Pinger {
addrs: make(map[string]*net.IPAddr), addrs: make(map[string]*net.IPAddr),
hasIPv4: false, hasIPv4: false,
hasIPv6: false, hasIPv6: false,
Size: TimeSliceLengh, Size: TimeSliceLength,
MaxRTT: time.Second, MaxRTT: time.Second,
OnRecv: nil, OnRecv: nil,
OnIdle: nil, OnIdle: nil,
@ -409,12 +406,16 @@ func (p *Pinger) sendICMP(conn, conn6 *net.IPConn) (map[string]*net.IPAddr, erro
t := timeToBytes(time.Now()) t := timeToBytes(time.Now())
if p.Size-TimeSliceLength != 0 {
t = append(t, byteSliceOfSize(p.Size-TimeSliceLength)...)
}
p.mu.Lock() p.mu.Lock()
bytes, err := (&icmpMessage{ bytes, err := (&icmpMessage{
Type: typ, Code: 0, Type: typ, Code: 0,
Body: &icmpEcho{ Body: &icmpEcho{
ID: p.id, Seq: p.seq, ID: p.id, Seq: p.seq,
Data: append(t, byteSliceOfSize(p.Size-TimeSliceLengh)...), Data: t,
}, },
}).Marshal() }).Marshal()
p.mu.Unlock() p.mu.Unlock()
@ -520,7 +521,7 @@ func (p *Pinger) procRecv(recv *packet, queue map[string]*net.IPAddr) {
case *icmpEcho: case *icmpEcho:
p.mu.Lock() p.mu.Lock()
if pkt.ID == p.id && pkt.Seq == p.seq { if pkt.ID == p.id && pkt.Seq == p.seq {
rtt = time.Since(bytesToTime(pkt.Data[:TimeSliceLengh])) rtt = time.Since(bytesToTime(pkt.Data[:TimeSliceLength]))
} }
p.mu.Unlock() p.mu.Unlock()
default: default:

View File

@ -252,3 +252,21 @@ func TestTimeToBytesToTime(t *testing.T) {
t.Errorf("bytesToTime failed: got %v, expected: %v", tm2.UTC(), tm.UTC()) t.Errorf("bytesToTime failed: got %v, expected: %v", tm2.UTC(), tm.UTC())
} }
} }
func TestPayloadSizeDefault(t *testing.T) {
s := timeToBytes(time.Now())
d := append(s, byteSliceOfSize(8-TimeSliceLength)...)
if len(d) != 8 {
t.Errorf("Payload size incorrect: got %d, expected: %d", len(d), 8)
}
}
func TestPayloadSizeCustom(t *testing.T) {
s := timeToBytes(time.Now())
d := append(s, byteSliceOfSize(64-TimeSliceLength)...)
if len(d) != 64 {
t.Errorf("Payload size incorrect: got %d, expected: %d", len(d), 64)
}
}