golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/icmp/ipv4_test.go (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package icmp
     6  
     7  import (
     8  	"encoding/binary"
     9  	"net"
    10  	"reflect"
    11  	"runtime"
    12  	"testing"
    13  
    14  	"golang.org/x/net/internal/socket"
    15  	"golang.org/x/net/ipv4"
    16  )
    17  
    18  func TestParseIPv4Header(t *testing.T) {
    19  	switch socket.NativeEndian {
    20  	case binary.LittleEndian:
    21  		t.Run("LittleEndian", func(t *testing.T) {
    22  			// TODO(mikio): Add platform dependent wire
    23  			// header formats when we support new
    24  			// platforms.
    25  			wireHeaderFromKernel := [ipv4.HeaderLen]byte{
    26  				0x45, 0x01, 0xbe, 0xef,
    27  				0xca, 0xfe, 0x45, 0xdc,
    28  				0xff, 0x01, 0xde, 0xad,
    29  				172, 16, 254, 254,
    30  				192, 168, 0, 1,
    31  			}
    32  			wireHeaderFromTradBSDKernel := [ipv4.HeaderLen]byte{
    33  				0x45, 0x01, 0xef, 0xbe,
    34  				0xca, 0xfe, 0x45, 0xdc,
    35  				0xff, 0x01, 0xde, 0xad,
    36  				172, 16, 254, 254,
    37  				192, 168, 0, 1,
    38  			}
    39  			th := &ipv4.Header{
    40  				Version:  ipv4.Version,
    41  				Len:      ipv4.HeaderLen,
    42  				TOS:      1,
    43  				TotalLen: 0xbeef,
    44  				ID:       0xcafe,
    45  				Flags:    ipv4.DontFragment,
    46  				FragOff:  1500,
    47  				TTL:      255,
    48  				Protocol: 1,
    49  				Checksum: 0xdead,
    50  				Src:      net.IPv4(172, 16, 254, 254),
    51  				Dst:      net.IPv4(192, 168, 0, 1),
    52  			}
    53  			var wh []byte
    54  			switch runtime.GOOS {
    55  			case "darwin", "ios":
    56  				wh = wireHeaderFromTradBSDKernel[:]
    57  			case "freebsd":
    58  				if freebsdVersion >= 1000000 {
    59  					wh = wireHeaderFromKernel[:]
    60  				} else {
    61  					wh = wireHeaderFromTradBSDKernel[:]
    62  				}
    63  			default:
    64  				wh = wireHeaderFromKernel[:]
    65  			}
    66  			h, err := ParseIPv4Header(wh)
    67  			if err != nil {
    68  				t.Fatal(err)
    69  			}
    70  			if !reflect.DeepEqual(h, th) {
    71  				t.Fatalf("got %#v; want %#v", h, th)
    72  			}
    73  		})
    74  	}
    75  }