当前位置: 首页>>代码示例>>Golang>>正文


Golang gopacket.Packet类代码示例

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


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

示例1: testSerialization

func testSerialization(t *testing.T, p gopacket.Packet, data []byte) {
	// Test re-serialization.
	slayers := []gopacket.SerializableLayer{}
	for _, l := range p.Layers() {
		slayers = append(slayers, l.(gopacket.SerializableLayer))
		if h, ok := l.(canSetNetLayer); ok {
			if err := h.SetNetworkLayerForChecksum(p.NetworkLayer()); err != nil {
				t.Fatal("can't set network layer:", err)
			}
		}
	}
	for _, opts := range []gopacket.SerializeOptions{
		gopacket.SerializeOptions{},
		gopacket.SerializeOptions{FixLengths: true},
		gopacket.SerializeOptions{ComputeChecksums: true},
		gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true},
	} {
		buf := gopacket.NewSerializeBuffer()
		err := gopacket.SerializeLayers(buf, opts, slayers...)
		if err != nil {
			t.Errorf("unable to reserialize layers with opts %#v: %v", opts, err)
		} else if !bytes.Equal(buf.Bytes(), data) {
			t.Errorf("serialization failure with opts %#v:\n---want---\n%v\n---got---\n%v\nBASH-colorized diff, want->got:\n%v", opts, hex.Dump(data), hex.Dump(buf.Bytes()), diffString(data, buf.Bytes()))
		}
	}
}
开发者ID:jcantrill,项目名称:geard,代码行数:26,代码来源:decode_test.go

示例2: readARP

// readARP watches a handle for incoming ARP responses we might care about, and prints them.
//
// readARP loops until 'stop' is closed.
func readARP(handle *pcap.Handle, iface *net.Interface, stop chan struct{}) {
	src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
	in := src.Packets()
	for {
		var packet gopacket.Packet
		select {
		case <-stop:
			return
		case packet = <-in:
			arpLayer := packet.Layer(layers.LayerTypeARP)
			if arpLayer == nil {
				continue
			}
			arp := arpLayer.(*layers.ARP)
			if arp.Operation != layers.ARPReply || bytes.Equal([]byte(iface.HardwareAddr), arp.SourceHwAddress) {
				// This is a packet I sent.
				continue
			}
			// Note:  we might get some packets here that aren't responses to ones we've sent,
			// if for example someone else sends US an ARP request.  Doesn't much matter, though...
			// all information is good information :)
			log.Printf("IP %v is at %v", net.IP(arp.SourceProtAddress), net.HardwareAddr(arp.SourceHwAddress))
		}
	}
}
开发者ID:dazer-chen,项目名称:gopacket,代码行数:28,代码来源:arpscan.go

示例3: checkLayers

func checkLayers(p gopacket.Packet, want []gopacket.LayerType, t *testing.T) {
	layers := p.Layers()
	t.Log("Checking packet layers, want", want)
	for _, l := range layers {
		t.Logf("  Got layer %v, %d bytes, payload of %d bytes", l.LayerType(),
			len(l.LayerContents()), len(l.LayerPayload()))
	}
	t.Log(p)
	if len(layers) != len(want) {
		t.Errorf("  Number of layers mismatch: got %d want %d", len(layers),
			len(want))
		return
	}
	for i, l := range layers {
		if l.LayerType() != want[i] {
			t.Errorf("  Layer %d mismatch: got %v want %v", i, l.LayerType(),
				want[i])
		}
	}
}
开发者ID:dazer-chen,项目名称:gopacket,代码行数:20,代码来源:base_test.go

示例4: handlePacket

func handlePacket(p gopacket.Packet) {
	ap := AP{}
	// extract beacon
	// extract Ssid
	for _, l := range p.Layers() {
		switch l.LayerType() {
		case layers.LayerTypeDot11MgmtBeacon:
			beacon, ok := p.Layer(layers.LayerTypeDot11MgmtBeacon).(*layers.Dot11MgmtBeacon)
			if !ok {
				log.Println("Could not marshal layer thing")
				continue
			}
			pack := gopacket.NewPacket(beacon.LayerContents(), layers.LayerTypeDot11MgmtBeacon, gopacket.Default)
			for _, subpack := range pack.Layers() {
				info, ok := subpack.(*layers.Dot11InformationElement)
				if !ok {
					continue
				}
				if info.ID == layers.Dot11InformationElementIDSSID {
					ap.Ssid = fmt.Sprintf("%s", info.Info)
					break
				}
			}
		case layers.LayerTypeDot11:
			base, ok := p.Layer(layers.LayerTypeDot11).(*layers.Dot11)
			if !ok {
				continue
			}
			ap.Bssid = base.Address2
			continue
		case layers.LayerTypeRadioTap:
			radio, ok := p.Layer(layers.LayerTypeRadioTap).(*layers.RadioTap)
			if !ok {
				continue
			}
			ap.Channel = radio.ChannelFrequency
			continue

		}
	}
	APList[ap.Ssid] = ap
}
开发者ID:WoLfh0UnD,项目名称:deauthdemo,代码行数:42,代码来源:deauth.go

示例5: handlePacket

func handlePacket(packet gopacket.Packet, counter chan *PacketCount) {
	appLayer := packet.ApplicationLayer()
	if appLayer == nil {
		return
	}

	if networkLayer := packet.NetworkLayer(); networkLayer != nil {
		srcIP := networkLayer.NetworkFlow().Src().String()
		dstIP := networkLayer.NetworkFlow().Dst().String()

		meta := packet.Metadata()
		counter <- &PacketCount{
			src:  srcIP,
			dst:  dstIP,
			size: uint64(meta.Length),
		}
	}
}
开发者ID:wwkeyboard,项目名称:tcpdump-remote-counter,代码行数:18,代码来源:main.go

示例6: handlePacket

// Packet information digestion ------------------------------------------------------
// function that takes the raw packet and creates a GPPacket structure from it. Initial
//  sanity checking has been performed in the function above, so we can now check whether
// the packet can be decoded directly
func (g *GPCapture) handlePacket(curPack gopacket.Packet) (*GPPacket, error) {

    // process metadata
    var numBytes uint16 = uint16(curPack.Metadata().CaptureInfo.Length)

    // read the direction from which the packet entered the interface
    isInboundTraffic := false
    if curPack.Metadata().CaptureInfo.Inbound == 1 {
        isInboundTraffic = true
    }

    // initialize vars (GO ensures that all variables are initialized with their
    // respective zero element)
    var (
        src, dst      []byte = zeroip, zeroip
        sp, dp        []byte = zeroport, zeroport

        // the default value is reserved by IANA and thus will never occur unless
        // the protocol could not be correctly identified 
        proto         byte   = 0xff
        fragBits      byte   = 0x00
        fragOffset    uint16
        TCPflags      uint8
        l7payload     []byte = zeropayload
        l7payloadSize uint16

        // size helper vars
        nlHeaderSize uint16
        tpHeaderSize uint16
    )

    // decode rest of packet
    if curPack.NetworkLayer() != nil {

	    nw_l := curPack.NetworkLayer().LayerContents()
        nlHeaderSize = uint16(len(nw_l))

        // exit if layer is available but the bytes aren't captured by the layer
        // contents
        if nlHeaderSize == 0 {
            return nil, errors.New("Network layer header not available")
        }

        // get ip info
        ipsrc, ipdst := curPack.NetworkLayer().NetworkFlow().Endpoints()

        src = ipsrc.Raw()
        dst = ipdst.Raw()

        // read out the next layer protocol
        switch curPack.NetworkLayer().LayerType() {
        case layers.LayerTypeIPv4:

            proto = nw_l[9]

	        // check for IP fragmentation
	        fragBits   = (0xe0 & nw_l[6]) >> 5
	        fragOffset = (uint16(0x1f & nw_l[6]) << 8) | uint16(nw_l[7])

	        // return decoding error if the packet carries anything other than the
	        // first fragment, i.e. if the packet lacks a transport layer header
	        if fragOffset != 0 {
                return nil, errors.New("Fragmented IP packet: offset: "+strconv.FormatUint(uint64(fragOffset), 10)+" flags: "+strconv.FormatUint(uint64(fragBits), 10))
	        }

        case layers.LayerTypeIPv6:
             proto = nw_l[6]
        }

        if curPack.TransportLayer() != nil {

            // get layer contents
            tp_l := curPack.TransportLayer().LayerContents()
            tpHeaderSize = uint16(len(tp_l))

            if tpHeaderSize == 0  {
                return nil, errors.New("Transport layer header not available")
            }

            // get port bytes
            psrc, dsrc := curPack.TransportLayer().TransportFlow().Endpoints()

            // only get raw bytes if we actually have TCP or UDP
            if proto == 6 || proto == 17 {
                sp = psrc.Raw()
                dp = dsrc.Raw()
            }

            // if the protocol is TCP, grab the flag information
            if proto == 6 {
                if tpHeaderSize < 14  {
                    return nil, errors.New("Incomplete TCP header: "+string(tp_l))
                }

                TCPflags = tp_l[13] // we are primarily interested in SYN, ACK and FIN
            }
//.........这里部分代码省略.........
开发者ID:kelixin,项目名称:goProbe,代码行数:101,代码来源:GPCapture.go

示例7: originalSize

func originalSize(packet gopacket.Packet) int {
	return len(packet.NetworkLayer().LayerPayload()) + len(packet.NetworkLayer().LayerContents())
}
开发者ID:aerobless,项目名称:IPSecDiagTool-Application,代码行数:3,代码来源:capture.go

示例8: getSrcDstIP

//Returns both the source & destination IP.
func getSrcDstIP(packet gopacket.Packet) (net.IP, net.IP) {
	ipLayer := packet.Layer(layers.LayerTypeIPv4)
	// Get IP data from this layer
	ip, _ := ipLayer.(*layers.IPv4)
	return ip.SrcIP, ip.DstIP
}
开发者ID:aerobless,项目名称:IPSecDiagTool-Application,代码行数:7,代码来源:capture.go


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