Пример #1
0
func (d *afpacket) Write(from ethernet.Frame) (err error) {
	copy(d.sockaddrLL.Addr[:6], []byte(from.Destination()))
	err = unix.Sendto(d.fd, []byte(from), 0, d.sockaddrLL)
	if err != nil {
		return
	}
	return
}
Пример #2
0
func TestWriteFrame(t *testing.T) {
	var (
		ifce *net.Interface
		err  error
		d    Dev
	)
	if ifce, err = net.InterfaceByName(*dev); err != nil {
		t.Fatalf("getting interface error: %v", err)
	}
	d, err = NewDev(ifce, nil)
	if err != nil {
		t.Fatal(err)
	}
	dst, err := net.ParseMAC("ff:ff:ff:ff:ff:ff")
	if err != nil {
		t.Fatal(err)
	}
	src, err := net.ParseMAC("12:34:56:78:9a:bc")
	if err != nil {
		t.Fatal(err)
	}
	var frame ethernet.Frame
	w := func() (err error) {
		(&frame).Prepare(dst, src, ethernet.NotTagged, ethernet.WSMP, 13)
		copy(frame.Payload(), "Hello, World!")
		err = d.Write(frame)
		if err != nil {
			return
		}
		return
	}
	for i := 0; i < 16; i++ {
		if nil != w() {
			t.Fatal(err)
		}
	}

	(&frame).Resize(d.Interface().MTU)
	if err = d.Write(frame); err != nil {
		t.Fatalf("writing frame with payload size equal to MTU fails: %v", err)
	}

	(&frame).Resize(d.Interface().MTU + 1)
	if nil == d.Write(frame) {
		t.Fatalf("writing frame with payload larger than MTU does not fail")
	}

	err = d.Close()
	if err != nil {
		t.Fatal(err)
	}

	if err = w(); nil == err {
		t.Fatal("closed Dev can still write")
	}
}
Пример #3
0
func (d *afpacket) Read(to *ethernet.Frame) (err error) {
	to.Resize(d.ifce.MTU)
	for {
		*to = (*to)[:cap(*to)]
		var n int
		n, _, err = unix.Recvfrom(d.fd, []byte(*to), 0)
		if err != nil {
			return
		}
		*to = (*to)[:n]
		if !equalMAC(to.Source(), d.ifce.HardwareAddr) && (d.filter == nil || d.filter(*to)) {
			return
		}
	}
}
Пример #4
0
func (d *bpfDev) Read(to *ethernet.Frame) (err error) {
	to.Resize(d.ifce.MTU)
	for {
		for d.p < d.n {
			hdr := (*bpfHdr)(unsafe.Pointer(&d.readBuf[d.p]))
			frameStart := d.p + int(hdr.hdrlen)
			n := int(hdr.caplen)
			*to = (*to)[:n]
			copy(*to, d.readBuf[frameStart:frameStart+n])
			d.p += bpfWordalign(int(hdr.hdrlen) + int(hdr.caplen))
			if !equalMAC(to.Source(), d.ifce.HardwareAddr) && (d.filter == nil || d.filter(*to)) {
				return
			}
		}

		d.n, err = d.fd.Read(d.readBuf)
		if err != nil {
			return
		}
		d.p = 0
	}
}
Пример #5
0
func TestReadFrame(t *testing.T) {
	var (
		ifce *net.Interface
		err  error
		d    Dev
	)
	if ifce, err = net.InterfaceByName(*dev); err != nil {
		t.Fatalf("getting interface error: %v", err)
	}
	d, err = NewDev(ifce, nil)
	if err != nil {
		t.Fatal(err)
	}
	var to ethernet.Frame
	for i := 0; i < 16; i++ {
		err = d.Read(&to)
		t.Logf("got frame: from %v to %v (ethertype %v): % x\n", to.Source(), to.Destination(), to.Ethertype(), to.Payload())
		if err != nil {
			t.Fatal(err)
		}
	}

	err = d.Close()
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 1024; i++ {
		err = d.Read(&to)
		if err != nil {
			break
		}
	}
	if err == nil {
		t.Fatal("closed Dev can still read")
	}
}