Pcap passes its tests

This commit is contained in:
Neale Pickett 2014-08-11 16:00:14 -06:00
parent d44fab1cb0
commit 134d923775
2 changed files with 23 additions and 11 deletions

View File

@ -2,9 +2,9 @@ package pcap
import ( import (
"time" "time"
"fmt"
"io" "io"
"encoding/binary" "encoding/binary"
"fmt"
) )
const MAXFRAME = 9000 const MAXFRAME = 9000
@ -95,7 +95,7 @@ func NewReader(r io.Reader) (*Reader, error) {
return ret, nil return ret, nil
} }
func (r *Reader) Read() (*Frame, error) { func (r *Reader) ReadFrame() (*Frame, error) {
var h FrameHeader var h FrameHeader
err := binary.Read(r.r, r.order, &h) err := binary.Read(r.r, r.order, &h)
@ -141,6 +141,10 @@ func NewWriter(w io.Writer) (*Writer, error) {
} }
func (w *Writer) WriteFrame(frame Frame) (error) { func (w *Writer) WriteFrame(frame Frame) (error) {
if frame.Header.Caplen != uint32(len(frame.Payload)) {
return fmt.Errorf("Caplen != len(Payload)")
}
if err := binary.Write(w.w, w.order, frame.Header); err != nil { if err := binary.Write(w.w, w.order, frame.Header); err != nil {
return err return err
} }

View File

@ -6,7 +6,6 @@ import (
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
"time"
) )
func randomString(prng *rand.Rand, length int) string { func randomString(prng *rand.Rand, length int) string {
@ -32,7 +31,7 @@ func TestReader(t *testing.T) {
} }
for { for {
frame, err := pin.Read() frame, err := pin.ReadFrame()
if err == io.EOF { if err == io.EOF {
break break
} }
@ -47,7 +46,7 @@ func TestReader(t *testing.T) {
} }
func TestReadWrite(t *testing.T) { func TestReadWrite(t *testing.T) {
prng := rand.New(rand.NewSource(time.Now().Unix())) prng := rand.New(rand.NewSource(58))
frames := make([]Frame, 20) frames := make([]Frame, 20)
outf := new(bytes.Buffer) outf := new(bytes.Buffer)
@ -56,28 +55,37 @@ func TestReadWrite(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
for _, f := range frames { for i, f := range frames {
f.Header.Sec = prng.Uint32() f.Header.Sec = prng.Uint32()
f.Header.Usec = prng.Uint32() f.Header.Usec = prng.Uint32()
f.Header.Caplen = prng.Uint32()
f.Header.Framelen = prng.Uint32() f.Header.Framelen = prng.Uint32()
f.Payload = randomString(prng, prng.Intn(400)) f.Payload = randomString(prng, prng.Intn(400))
f.Header.Caplen = uint32(len(f.Payload))
pout.WriteFrame(f) err := pout.WriteFrame(f); if err != nil {
t.Fatal(err)
}
frames[i] = f
} }
pin, err := NewReader(outf) pin, err := NewReader(outf)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
for _, f := range frames {
ff, err := pin.Read() if pout.Header != pin.Header {
t.Fatal("Headers differ")
}
for i, f := range frames {
ff, err := pin.ReadFrame()
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if *ff != f { if *ff != f {
t.Fatal(ff, f) t.Fatalf("Frame %d compare failed", i)
} }
} }
} }