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:
parent
1a8c22e90d
commit
56843b1f9f
15
fastping.go
15
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:
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user