From 56843b1f9ff3f4fd67a244ddcc0098f575eee8e2 Mon Sep 17 00:00:00 2001 From: Simon Whitehead Date: Thu, 6 Nov 2014 08:28:54 +1100 Subject: [PATCH] Fixed payload size. Added tests. --- fastping.go | 15 ++++++++------- fastping_test.go | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/fastping.go b/fastping.go index 5ead15f..c7ca0c4 100644 --- a/fastping.go +++ b/fastping.go @@ -47,12 +47,9 @@ import ( "time" ) -const TimeSliceLengh = 8 +const TimeSliceLength = 8 func byteSliceOfSize(n int) []byte { - if n == 0 { - n = TimeSliceLengh // if its 0 .. default it to 8 - } b := make([]byte, n) for i := 0; i < len(b); i++ { b[i] = 1 @@ -139,7 +136,7 @@ func NewPinger() *Pinger { addrs: make(map[string]*net.IPAddr), hasIPv4: false, hasIPv6: false, - Size: TimeSliceLengh, + Size: TimeSliceLength, MaxRTT: time.Second, OnRecv: nil, OnIdle: nil, @@ -409,12 +406,16 @@ func (p *Pinger) sendICMP(conn, conn6 *net.IPConn) (map[string]*net.IPAddr, erro t := timeToBytes(time.Now()) + if p.Size-TimeSliceLength != 0 { + t = append(t, byteSliceOfSize(p.Size-TimeSliceLength)...) + } + p.mu.Lock() bytes, err := (&icmpMessage{ Type: typ, Code: 0, Body: &icmpEcho{ ID: p.id, Seq: p.seq, - Data: append(t, byteSliceOfSize(p.Size-TimeSliceLengh)...), + Data: t, }, }).Marshal() p.mu.Unlock() @@ -520,7 +521,7 @@ func (p *Pinger) procRecv(recv *packet, queue map[string]*net.IPAddr) { case *icmpEcho: p.mu.Lock() 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() default: diff --git a/fastping_test.go b/fastping_test.go index fc5d683..cef5ab9 100644 --- a/fastping_test.go +++ b/fastping_test.go @@ -252,3 +252,21 @@ func TestTimeToBytesToTime(t *testing.T) { 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) + } +}