github.com/labulakalia/water@v0.0.5-0.20231118024244-f351ca6784b6/ipv4_test.go (about)

     1  package water
     2  
     3  import (
     4  	"net"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/labulakalia/water/waterutil"
     9  )
    10  
    11  const BUFFERSIZE = 1522
    12  
    13  func startRead(t *testing.T, ifce *Interface) (dataChan <-chan []byte, errChan <-chan error) {
    14  
    15  	dataCh := make(chan []byte)
    16  	errCh := make(chan error)
    17  	go func() {
    18  		for {
    19  			buffer := make([]byte, BUFFERSIZE)
    20  			n, err := ifce.Read(buffer)
    21  			if err != nil {
    22  				errCh <- err
    23  			} else {
    24  				buffer = buffer[:n:n]
    25  				dataCh <- buffer
    26  			}
    27  		}
    28  	}()
    29  	return dataCh, errCh
    30  }
    31  
    32  func waitForPingOrBust(t *testing.T,
    33  	isTAP bool,
    34  	expectBroadcast bool,
    35  	expectSrc net.IP,
    36  	expectDest net.IP,
    37  	dataCh <-chan []byte, errCh <-chan error) {
    38  	waitForPintTimeout := time.NewTimer(8 * time.Second).C
    39  readFrame:
    40  	for {
    41  		select {
    42  		case buffer := <-dataCh:
    43  			var packet []byte
    44  			if isTAP {
    45  				ethertype := waterutil.MACEthertype(buffer)
    46  				if ethertype != waterutil.IPv4 {
    47  					continue readFrame
    48  				}
    49  				if expectBroadcast && !waterutil.IsBroadcast(waterutil.MACDestination(buffer)) {
    50  					continue readFrame
    51  				}
    52  				packet = waterutil.MACPayload(buffer)
    53  			} else {
    54  				packet = buffer
    55  			}
    56  			if !waterutil.IsIPv4(packet) {
    57  				continue readFrame
    58  			}
    59  			if !waterutil.IPv4Source(packet).Equal(expectSrc) {
    60  				continue readFrame
    61  			}
    62  			if !waterutil.IPv4Destination(packet).Equal(expectDest) {
    63  				continue readFrame
    64  			}
    65  			if waterutil.IPv4Protocol(packet) != waterutil.ICMP {
    66  				continue readFrame
    67  			}
    68  			t.Logf("received broadcast frame: %#v\n", buffer)
    69  			break readFrame
    70  		case err := <-errCh:
    71  			t.Fatalf("read error: %v", err)
    72  		case <-waitForPintTimeout:
    73  			t.Fatal("Waiting for broadcast packet timeout")
    74  		}
    75  	}
    76  }