• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang gopacket.NewPacket函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/google/gopacket.NewPacket函数的典型用法代码示例。如果您正苦于以下问题:Golang NewPacket函数的具体用法?Golang NewPacket怎么用?Golang NewPacket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewPacket函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Testv4Defrag

func Testv4Defrag(t *testing.T) {
	nomalPack := make(chan gopacket.Packet, 5)
	fragV4Pack := make(chan gopacket.Packet, 5)
	go v4Defrag(fragV4Pack, nomalPack)
	pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack1
	pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack2
	pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack3
	pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
	fragV4Pack <- pack4
	result := <-nomalPack
	ip := result.Layer(layers.LayerTypeIPv4)
	//TEST if the ip matches expectation
	if ip == nil {
		t.Errorf("defrag does not return IPV4 LAYER")
	}
	if len(ip.LayerPayload()) != 4508 {
		t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
	}

	validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
	validPayload = append(validPayload, testPing1Frag3[34:]...)
	validPayload = append(validPayload, testPing1Frag4[34:]...)

	if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
		fmt.Println(bytediff.BashOutput.String(
			bytediff.Diff(validPayload, ip.LayerPayload())))
		t.Errorf("defrag: payload is not correctly defragmented")
	}
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:32,代码来源:main_test.go


示例2: TestUDPPacketVXLANGetInnerEthernetLayer

func TestUDPPacketVXLANGetInnerEthernetLayer(t *testing.T) {
	p := gopacket.NewPacket(testUDPPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	// show how to extract the inner ethernet header
	vxlan := p.Layer(LayerTypeVxlan)
	p2 := gopacket.NewPacket(vxlan.LayerPayload(), LinkTypeEthernet, gopacket.Default)
	ethernetL := p2.Layer(LayerTypeEthernet)
	ethernet, _ := ethernetL.(*Ethernet)
	if ethernet == nil {
		t.Error("Failed to find ethernet header")
	}
	dstmac := net.HardwareAddr{0x00, 0x30, 0x88, 0x01, 0x00, 0x02}
	srcmac := net.HardwareAddr{0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04}
	if ethernet.DstMAC[0] != dstmac[0] &&
		ethernet.DstMAC[1] != dstmac[1] &&
		ethernet.DstMAC[2] != dstmac[2] &&
		ethernet.DstMAC[3] != dstmac[3] &&
		ethernet.DstMAC[4] != dstmac[4] &&
		ethernet.DstMAC[5] != dstmac[5] &&
		ethernet.SrcMAC[0] != srcmac[0] &&
		ethernet.SrcMAC[1] != srcmac[1] &&
		ethernet.SrcMAC[2] != srcmac[2] &&
		ethernet.SrcMAC[3] != srcmac[3] &&
		ethernet.SrcMAC[4] != srcmac[4] &&
		ethernet.SrcMAC[5] != srcmac[5] &&
		ethernet.EthernetType != 0x0800 {
		t.Error("Decoded packet incorrect values")
	}

}
开发者ID:ccordes-snaproute,项目名称:gopacket,代码行数:32,代码来源:vxlan_test.go


示例3: main

func main() {
	// If we don't have a handle to a device or a file, but we have a bunch
	// of raw bytes, we can try to decode them in to packet information

	// NewPacket() takes the raw bytes that make up the packet as the first parameter
	// The second parameter is the lowest level layer you want to decode. It will
	// decode that layer and all layers on top of it. The third layer
	// is the type of decoding: default(all at once), lazy(on demand), and NoCopy
	// which will not create a copy of the buffer

	// Create an packet with ethernet, IP, TCP, and payload layers
	// We are creating one we know will be decoded properly but
	// your byte source could be anything. If any of the packets
	// come back as nil, that means it could not decode it in to
	// the proper layer (malformed or incorrect packet type)
	payload := []byte{2, 4, 6}
	options := gopacket.SerializeOptions{}
	buffer := gopacket.NewSerializeBuffer()
	gopacket.SerializeLayers(buffer, options,
		&layers.Ethernet{},
		&layers.IPv4{},
		&layers.TCP{},
		gopacket.Payload(payload),
	)
	rawBytes := buffer.Bytes()

	// Decode an ethernet packet
	ethPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeEthernet,
			gopacket.Default,
		)

	// with Lazy decoding it will only decode what it needs when it needs it
	// This is not concurrency safe. If using concurrency, use default
	ipPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeIPv4,
			gopacket.Lazy,
		)

	// With the NoCopy option, the underlying slices are referenced
	// directly and not copied. If the underlying bytes change so will
	// the packet
	tcpPacket :=
		gopacket.NewPacket(
			rawBytes,
			layers.LayerTypeTCP,
			gopacket.NoCopy,
		)

	fmt.Println(ethPacket)
	fmt.Println(ipPacket)
	fmt.Println(tcpPacket)
}
开发者ID:tjyang,项目名称:reference,代码行数:57,代码来源:bytes_to_packet.go


示例4: Testv4Defrag

func Testv4Defrag(t *testing.T) {
	v4defragger := ip4defrag.NewIPv4Defragmenter()
	pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
	pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
	pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
	pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
	result, err := v4defragger.DefragIPv4(pack1.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack1")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack1")
	}
	result, err = v4defragger.DefragIPv4(pack2.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack2")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack2")
	}
	result, err = v4defragger.DefragIPv4(pack3.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack3")
	}
	if result != nil {
		t.Fatalf("unexpected defragmented packet after pack3")
	}
	result, err = v4defragger.DefragIPv4(pack4.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Fatalf("error defragmenting pack4")
	}
	if result == nil {
		t.Fatalf("missing defragmented packet after pack4")
	}
	ip := result
	// TEST if the ip matches expectation
	if ip == nil {
		t.Errorf("defrag does not return IPV4 LAYER")
	}
	if len(ip.LayerPayload()) != 4508 {
		t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
	}

	validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
	validPayload = append(validPayload, testPing1Frag3[34:]...)
	validPayload = append(validPayload, testPing1Frag4[34:]...)

	if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
		fmt.Println(bytediff.BashOutput.String(
			bytediff.Diff(validPayload, ip.LayerPayload())))
		t.Errorf("defrag: payload is not correctly defragmented")
	}
}
开发者ID:RunxiaWan,项目名称:PcapParser,代码行数:53,代码来源:main_test.go


示例5: Layers

// Layers returns gopacket layer representation of this frame. layers contents are all pointer to struct,
// so you can modify the frame information simply setting values to the slice contents directly.
func (self *Frame) Layers() []gopacket.Layer {
	if len(self.serialized) != 0 {
		self.layers = gopacket.NewPacket(self.serialized, layers.LinkTypeEthernet, gopacket.Lazy).Layers()
		self.serialized = self.serialized[:0]
	}
	return self.layers
}
开发者ID:hkwi,项目名称:gopenflow,代码行数:9,代码来源:frame.go


示例6: getack

func getack(conn net.PacketConn, srcport layers.TCPPort, dstip string) (ack uint32, err error) {
	for {
		b := make([]byte, 4096)
		log.Println("reading from conn")
		var n int
		var addr net.Addr
		n, addr, err = conn.ReadFrom(b)
		if err != nil {
			log.Println("reading..", err)
			return
		} else if addr.String() == dstip {
			// Decode a packet
			packet := gopacket.NewPacket(b[:n], layers.LayerTypeTCP, gopacket.Default)
			// Get the TCP layer from this packet
			if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
				tcp, _ := tcpLayer.(*layers.TCP)
				if tcp.DstPort == srcport {
					if tcp.SYN && tcp.ACK {
						ack = tcp.Seq
					} else {
						err = errors.New("Port is CLOSED")
					}
					return
				}
			}
		} else {
			err = errors.New("Got packet not matching addr")
		}
	}
	return
}
开发者ID:turbobytes,项目名称:initcwndcheck,代码行数:31,代码来源:initcwndcheck.go


示例7: v4Defrag

func v4Defrag(v4frag chan gopacket.Packet, normalPack chan gopacket.Packet) error {
	defragger := ip4defrag.NewIPv4Defragmenter()
	for {
		fragpack := <-v4frag
		layer := fragpack.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
		in, err := defragger.DefragIPv4(layer)
		if err != nil {
			return err //error handle
		} else if in == nil { //part of fragment continue
			continue
		} else {
			b := gopacket.NewSerializeBuffer()
			ops := gopacket.SerializeOptions{
				FixLengths:       true,
				ComputeChecksums: true,
			}
			// it should be remebered that you should copy the payload in when you use SerializeTo
			ip_payload, _ := b.PrependBytes(len(in.Payload))
			copy(ip_payload, in.Payload)
			in.SerializeTo(b, ops)
			resultPack := gopacket.NewPacket(b.Bytes(), layers.LayerTypeIPv4, gopacket.Default)
			err := resultPack.ErrorLayer()
			if err != nil {
				fmt.Println("Error decoding some part of the packet:", err) //need error handle here
				//return
				continue
			}
			resultPack.Metadata().CaptureLength = len(resultPack.Data())
			resultPack.Metadata().Length = len(resultPack.Data())
			fmt.Println("defrag a package")
			normalPack <- resultPack
		}
	}
	return nil
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:35,代码来源:main.go


示例8: main

func main() {
	var err error
	var ci gopacket.CaptureInfo
	var frame []byte
	sniffer, err := bsdbpf.NewBPFSniffer("alc0", nil)
	if err != nil {
		panic(err)
	}
	for {
		frame, ci, err = sniffer.ReadPacketData()
		if err != nil {
			panic(err)
		}
		fmt.Printf("timeStamp %s\n", ci.Timestamp)
		packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)

		// Get the TCP layer from this packet
		if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
			fmt.Println("This is a TCP packet!")
			// Get actual TCP data from this layer
			tcp, _ := tcpLayer.(*layers.TCP)
			fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
		}

		// Iterate over all layers, printing out each layer type
		for _, layer := range packet.Layers() {
			fmt.Println("PACKET LAYER:", layer.LayerType())
		}
	}
}
开发者ID:hb9cwp,项目名称:rsTestGopacket,代码行数:30,代码来源:testBPFsniffer.go


示例9: TestPacketDot11DataIP

func TestPacketDot11DataIP(t *testing.T) {
	p := gopacket.NewPacket(testPacketDot11DataIP, LinkTypeIEEE80211Radio, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeIPv4, LayerTypeUDP, gopacket.LayerTypePayload}, t)
}
开发者ID:gusev-vitaliy,项目名称:gopacket,代码行数:7,代码来源:dot11_test.go


示例10: TestDHCPv4EncodeResponse

func TestDHCPv4EncodeResponse(t *testing.T) {
	dhcp := &DHCPv4{Operation: DHCPOpReply, HardwareType: LinkTypeEthernet, Xid: 0x12345678,
		ClientIP: net.IP{0, 0, 0, 0}, YourClientIP: net.IP{192, 168, 0, 123}, NextServerIP: net.IP{192, 168, 0, 1}, RelayAgentIP: net.IP{0, 0, 0, 0},
		ClientHWAddr: net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
		ServerName:   make([]byte, 64), File: make([]byte, 128)}

	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptMessageType, []byte{byte(DHCPMsgTypeOffer)}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptSubnetMask, []byte{255, 255, 255, 0}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT1, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT2, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptLeaseTime, []byte{0x00, 0x00, 0x0e, 0x10}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptServerID, []byte{192, 168, 0, 1}))

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{FixLengths: true}
	err := gopacket.SerializeLayers(buf, opts, dhcp)
	if err != nil {
		t.Fatal(err)
	}

	p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDHCPv4, testDecodeOptions)
	dhcp2 := p2.Layer(LayerTypeDHCPv4).(*DHCPv4)
	testDHCPEqual(t, dhcp, dhcp2)
	fmt.Print(p2)
}
开发者ID:jesseward,项目名称:gopacket,代码行数:25,代码来源:dhcp_test.go


示例11: TestVRRPPacketPacket0

func TestVRRPPacketPacket0(t *testing.T) {
	p := gopacket.NewPacket(vrrpPacketPriority100, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeVRRP}, t)

	// Version=2 Type=VRRPv2 Advertisement VirtualRtrID=1 Priority=100
	vrrp := p.Layer(LayerTypeVRRP).(*VRRPv2)
	if vrrp.Version != 2 {
		t.Fatalf("Unable to decode VRRPv2 version. Received %d, expected %d", vrrp.Version, 2)
	}

	if vrrp.Type != 1 {
		t.Fatalf("Unable to decode VRRPv2 type. Received %d, expected %d", vrrp.Type, 1)
	}

	if vrrp.Priority != 100 {
		t.Fatalf("Unable to decode VRRPv2 priority. Received %d, expected %d", vrrp.Priority, 100)
	}

	if vrrp.Checksum != 47698 {
		t.Fatalf("Unable to decode VRRPv2 checksum. Received %d, expected %d", vrrp.Checksum, 47698)
	}
}
开发者ID:cdshann,项目名称:minimega,代码行数:25,代码来源:vrrp_test.go


示例12: Rcv

func (h *arpPktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {
	pin := msg.Data().(nom.PacketIn)
	p := gopacket.NewPacket([]byte(pin.Packet), layers.LayerTypeEthernet, gopacket.Default)
	etherlayer := p.Layer(layers.LayerTypeEthernet)

	if etherlayer == nil {
		return nil
	}

	e, _ := etherlayer.(*layers.Ethernet)

	if e.EthernetType != layers.EthernetTypeARP {
		return nil
	}

	host, _, err := decodeARP([]byte(pin.Packet))
	host.Node = pin.Node

	if err != nil {
		glog.Errorf("ARP decoding error: %v", err)
		return err
	}
	glog.V(2).Infof("Host detected: %v", host)

	ctx.Emit(nom.HostConnected(host))

	return nil
}
开发者ID:1995parham,项目名称:FlyNest,代码行数:28,代码来源:host.go


示例13: TestPacketVXLAN

func TestPacketVXLAN(t *testing.T) {
	p := gopacket.NewPacket(testPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeVXLAN, LayerTypeEthernet, LayerTypeIPv4, LayerTypeICMPv4, gopacket.LayerTypePayload}, t)
	if got, ok := p.Layer(LayerTypeVXLAN).(*VXLAN); ok {
		want := &VXLAN{
			BaseLayer: BaseLayer{
				Contents: []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00},
				Payload: []byte{0x00, 0x30, 0x88, 0x01, 0x00, 0x02, 0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04, 0x08, 0x00,
					0x45, 0x00, 0x00, 0x54, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01, 0x23, 0x4f, 0xc0, 0xa8, 0xcb, 0x03,
					0xc0, 0xa8, 0xcb, 0x05, 0x08, 0x00, 0xf6, 0xf2, 0x05, 0x0c, 0x00, 0x01, 0xfc, 0xe2, 0x97, 0x51,
					0x00, 0x00, 0x00, 0x00, 0xa6, 0xf8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13,
					0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
					0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33,
					0x34, 0x35, 0x36, 0x37},
			},
			ValidIDFlag:      true,
			VNI:              255,
			GBPExtension:     false,
			GBPApplied:       false,
			GBPDontLearn:     false,
			GBPGroupPolicyID: 0,
		}
		if !reflect.DeepEqual(want, got) {
			t.Errorf("VXLAN layer mismatch, \nwant %#v\ngot %#v\n", want, got)
		}
	}
}
开发者ID:jesseward,项目名称:gopacket,代码行数:30,代码来源:vxlan_test.go


示例14: runReader

func (vnet *VNET) runReader(ctx context.Context) {
	defer vnet.wg.Done()

	var maxPktSize = vnet.iface.MaxPacketSize()

	for {
		var pkt = NewPacket(maxPktSize)

		n, flags, err := vnet.iface.ReadPacket(pkt.buf)
		if err == io.EOF {
			pkt.Release()
			return
		}
		if err != nil {
			pkt.Release()
			log.Printf("error during read: %s", err)
			time.Sleep(10 * time.Millisecond)
			continue
		}

		pkt.Packet = gopacket.NewPacket(pkt.buf[:n], layers.LayerTypeEthernet, gopacket.NoCopy)
		pkt.Flags = flags
		pkt.layers = pkt.Layers()

		vnet.dispatch(ctx, pkt)
	}
}
开发者ID:fd,项目名称:switchboard,代码行数:27,代码来源:dispatcher.go


示例15: TestPacketUSB0

func TestPacketUSB0(t *testing.T) {
	p := gopacket.NewPacket(testPacketUSB0, LinkTypeLinuxUSB, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeUSB, LayerTypeUSBInterrupt}, t)

	if got, ok := p.Layer(LayerTypeUSB).(*USB); ok {
		want := &USB{
			BaseLayer: BaseLayer{
				Contents: []uint8{0x0, 0x38, 0x4a, 0x3b, 0x0, 0x88, 0xff, 0xff, 0x43, 0x1, 0x81, 0x1, 0x2, 0x0, 0x2d, 0x0, 0xc0, 0xd3, 0x5b, 0x50, 0x0, 0x0, 0x0, 0x0, 0x8a, 0x85, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0},
				Payload:  []uint8{0x4},
			},
			ID:             0xffff88003b4a3800,
			EventType:      USBEventTypeComplete,
			TransferType:   USBTransportTypeInterrupt,
			Direction:      0x1,
			EndpointNumber: 0x1,
			DeviceAddress:  0x1,
			BusID:          0x2,
			TimestampSec:   1348195264,
			TimestampUsec:  689546,
			Setup:          false,
			Data:           true,
			Status:         0,
			UrbLength:      0x1,
			UrbDataLength:  0x1,
		}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("USB packet processing failed:\ngot  :\n%#v\n\nwant :\n%#v\n\n", got, want)
		}
	}

}
开发者ID:hgGeorg,项目名称:mongo,代码行数:35,代码来源:usb_test.go


示例16: TestDHCPv4EncodeRequest

func TestDHCPv4EncodeRequest(t *testing.T) {
	dhcp := &DHCPv4{Operation: DHCPOpRequest, HardwareType: LinkTypeEthernet, Xid: 0x12345678,
		ClientIP: net.IP{0, 0, 0, 0}, YourClientIP: net.IP{0, 0, 0, 0}, NextServerIP: net.IP{0, 0, 0, 0}, RelayAgentIP: net.IP{0, 0, 0, 0},
		ClientHWAddr: net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
		ServerName:   make([]byte, 64), File: make([]byte, 128)}

	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptMessageType, []byte{byte(DHCPMsgTypeDiscover)}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptHostname, []byte{'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm'}))
	dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptParamsRequest,
		[]byte{byte(DHCPOptSubnetMask), byte(DHCPOptBroadcastAddr), byte(DHCPOptTimeOffset),
			byte(DHCPOptRouter), byte(DHCPOptDomainName), byte(DHCPOptDNS), byte(DHCPOptDomainSearch),
			byte(DHCPOptHostname), byte(DHCPOptNetBIOSTCPNS), byte(DHCPOptInterfaceMTU), byte(DHCPOptClasslessStaticRoute),
			byte(DHCPOptNTPServers)}))

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{FixLengths: true}
	err := gopacket.SerializeLayers(buf, opts, dhcp)
	if err != nil {
		t.Fatal(err)
	}

	p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDHCPv4, testDecodeOptions)
	dhcp2 := p2.Layer(LayerTypeDHCPv4).(*DHCPv4)
	testDHCPEqual(t, dhcp, dhcp2)
}
开发者ID:jesseward,项目名称:gopacket,代码行数:25,代码来源:dhcp_test.go


示例17: decodeInGRELayer

func decodeInGRELayer(data []byte, p gopacket.PacketBuilder) error {
	switch (data[0] >> 4) & 0xf {
	case 4:
		ip4 := &layers.IPv4{}
		err := ip4.DecodeFromBytes(data, p)
		p.AddLayer(ip4)
		p.SetNetworkLayer(ip4)
		if err != nil {
			return err
		}
		return p.NextDecoder(ip4.NextLayerType())
	case 6:
		ip6 := &layers.IPv6{}
		err := ip6.DecodeFromBytes(data, p)
		p.AddLayer(ip6)
		p.SetNetworkLayer(ip6)
		if err != nil {
			return err
		}
		return p.NextDecoder(ip6.NextLayerType())
	}
	packet := gopacket.NewPacket(data, layers.LayerTypeARP, gopacket.Lazy)
	layer := packet.Layer(layers.LayerTypeARP)

	p.AddLayer(layer)

	return nil
}
开发者ID:nplanel,项目名称:skydive,代码行数:28,代码来源:decoder.go


示例18: TestPacketDot11DataARP

func TestPacketDot11DataARP(t *testing.T) {
	p := gopacket.NewPacket(testPacketDot11DataARP, LinkTypeIEEE80211Radio, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeARP}, t)

	if got, ok := p.Layer(LayerTypeARP).(*ARP); ok {
		want := &ARP{
			BaseLayer: BaseLayer{
				Contents: []uint8{0x0, 0x1, 0x8, 0x0, 0x6, 0x4, 0x0, 0x1, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52, 0xa9, 0xfe, 0xf7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x43, 0x8, 0xe, 0x36},
				Payload:  []uint8{},
			},
			AddrType:          0x1,
			Protocol:          0x800,
			HwAddressSize:     0x6,
			ProtAddressSize:   0x4,
			Operation:         0x1,
			SourceHwAddress:   []uint8{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52},
			SourceProtAddress: []uint8{0xa9, 0xfe, 0xf7, 0x0},
			DstHwAddress:      []uint8{0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
			DstProtAddress:    []uint8{0x43, 0x8, 0xe, 0x36},
		}

		if !reflect.DeepEqual(got, want) {
			t.Errorf("ARP packet processing failed:\ngot  :\n%#v\n\nwant :\n%#v\n\n", got, want)
		}
	}
}
开发者ID:gusev-vitaliy,项目名称:gopacket,代码行数:29,代码来源:dot11_test.go


示例19: checkNTP

// checkNTP() uses the ntp.go code to analyse the packet bytes as an NTP UDP
// packet and generate an NTP object. It then compares the generated NTP object
// with the one provided and raises the alarm if there is any difference.
// The desc argument is output with any failure message to identify the test.
func checkNTP(desc string, t *testing.T, packetBytes []byte, pExpectedNTP *NTP) {

	// Analyse the packet bytes, yielding a new packet object p.
	p := gopacket.NewPacket(packetBytes, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Errorf("Failed to decode packet %s: %v", desc, p.ErrorLayer().Error())
	}

	// Ensure that the packet analysis yielded the correct set of layers:
	//    Link Layer        = Ethernet.
	//    Network Layer     = IPv4.
	//    Transport Layer   = UDP.
	//    Application Layer = NTP.
	checkLayers(p, []gopacket.LayerType{
		LayerTypeEthernet,
		LayerTypeIPv4,
		LayerTypeUDP,
		LayerTypeNTP}, t)

	// Select the Application (NTP) layer.
	pResultNTP, ok := p.ApplicationLayer().(*NTP)
	if !ok {
		t.Error("No NTP layer type found in packet in " + desc + ".")
	}

	// Compare the generated NTP object with the expected NTP object.
	if !reflect.DeepEqual(pResultNTP, pExpectedNTP) {
		t.Errorf("NTP packet processing failed for packet "+desc+
			":\ngot  :\n%#v\n\nwant :\n%#v\n\n", pResultNTP, pExpectedNTP)
	}
}
开发者ID:jesseward,项目名称:gopacket,代码行数:35,代码来源:ntp_test.go


示例20: TestUDPPacketVXLAN

func TestUDPPacketVXLAN(t *testing.T) {
	p := gopacket.NewPacket(testUDPPacketVXLAN, LinkTypeEthernet, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4,
		LayerTypeUDP, LayerTypeVxlan, LayerTypeEthernet, LayerTypeIPv4,
		LayerTypeICMPv4, gopacket.LayerTypePayload}, t)

	vxlanL := p.Layer(LayerTypeVxlan)
	if vxlanL == nil {
		t.Fatal("Failed to get a pointer to VXLAN struct")
	}
	vxlan, _ := vxlanL.(*VXLAN)
	if vxlan.Flags != 0x08 {
		t.Fatal("Failed to decode Flags properly")
	}

	if vxlan.VNI[0] != 0x00 ||
		vxlan.VNI[1] != 0x00 ||
		vxlan.VNI[2] != 0x00 {
		t.Fatal("Failed to decode VNI properly")
	}

}
开发者ID:ccordes-snaproute,项目名称:gopacket,代码行数:25,代码来源:vxlan_test.go



注:本文中的github.com/google/gopacket.NewPacket函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang gopacket.NewPacketSource函数代码示例发布时间:2022-05-23
下一篇:
Golang gopacket.NewFlow函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap