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


Golang layers.IPv4类代码示例

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


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

示例1: decodePackets

func (i *Sniffer) decodePackets() {
	var eth layers.Ethernet
	var ip layers.IPv4
	var tcp layers.TCP
	var payload gopacket.Payload

	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip, &tcp, &payload)
	decoded := make([]gopacket.LayerType, 0, 4)

	for {
		select {
		case <-i.stopDecodeChan:
			return
		case timedRawPacket := <-i.decodePacketChan:
			newPayload := new(gopacket.Payload)
			payload = *newPayload
			err := parser.DecodeLayers(timedRawPacket.RawPacket, &decoded)
			if err != nil {
				continue
			}
			flow := types.NewTcpIpFlowFromFlows(ip.NetworkFlow(), tcp.TransportFlow())
			packetManifest := types.PacketManifest{
				Timestamp: timedRawPacket.Timestamp,
				Flow:      flow,
				RawPacket: timedRawPacket.RawPacket,
				IP:        ip,
				TCP:       tcp,
				Payload:   payload,
			}
			i.dispatcher.ReceivePacket(&packetManifest)
		}
	}
}
开发者ID:roger2000hk,项目名称:HoneyBadger,代码行数:33,代码来源:sniffer.go

示例2: fragment

func fragment(eth layers.Ethernet, ip layers.IPv4, mtu int,
	forward func([]byte)) error {
	// We are not doing any sort of NAT, so we don't need to worry
	// about checksums of IP payload (eg UDP checksum).
	headerSize := int(ip.IHL) * 4
	// &^ is bit clear (AND NOT). So here we're clearing the lowest 3
	// bits.
	maxSegmentSize := (mtu - headerSize) &^ 7
	opts := gopacket.SerializeOptions{
		FixLengths:       false,
		ComputeChecksums: true}
	payloadSize := int(ip.Length) - headerSize
	payload := ip.BaseLayer.Payload[:payloadSize]
	offsetBase := int(ip.FragOffset) << 3
	origFlags := ip.Flags
	ip.Flags = ip.Flags | layers.IPv4MoreFragments
	ip.Length = uint16(headerSize + maxSegmentSize)
	if eth.EthernetType == layers.EthernetTypeLLC {
		// using LLC, so must set eth length correctly. eth length
		// is just the length of the payload
		eth.Length = ip.Length
	} else {
		eth.Length = 0
	}
	for offset := 0; offset < payloadSize; offset += maxSegmentSize {
		var segmentPayload []byte
		if len(payload) <= maxSegmentSize {
			// last one
			segmentPayload = payload
			ip.Length = uint16(len(payload) + headerSize)
			ip.Flags = origFlags
			if eth.EthernetType == layers.EthernetTypeLLC {
				eth.Length = ip.Length
			} else {
				eth.Length = 0
			}
		} else {
			segmentPayload = payload[:maxSegmentSize]
			payload = payload[maxSegmentSize:]
		}
		ip.FragOffset = uint16((offset + offsetBase) >> 3)
		buf := gopacket.NewSerializeBuffer()
		segPayload := gopacket.Payload(segmentPayload)
		err := gopacket.SerializeLayers(buf, opts, &eth, &ip,
			&segPayload)
		if err != nil {
			return err
		}

		forward(buf.Bytes())
	}
	return nil
}
开发者ID:jepsenwan,项目名称:weave,代码行数:53,代码来源:sleeve.go

示例3: craftAnswer

/*
    FUNCTION: craftAnswer(ethernetLayer *layers.Ethernet, ipLayer *layers.IPv4, dnsLayer *layers.DNS, udpLayer *layers.UDP) []byte{
    RETURNS: Byte array containing the spoofed response DNS packet data
    ARGUMENTS:
								*layers.Ethernet ethernetLayer - the ethernet part of the packet recieved
								*layers.DNS dnsLayer - the dns part of the packet recieved
                *layers.IPv4 ipLayer - the ip part of the packet recieved
                *layers.UDP udpLayer - the udp part of the packet recieved

    ABOUT:
    Crafts a spoofed dns packet using the incoming query.
*/
func craftAnswer(ethernetLayer *layers.Ethernet, ipLayer *layers.IPv4, dnsLayer *layers.DNS, udpLayer *layers.UDP) []byte {

	//if not a question return
	if dnsLayer.QR || ipLayer.SrcIP.String() != target {
		return nil
	}

	//must build every layer to send DNS packets
	ethMac := ethernetLayer.DstMAC
	ethernetLayer.DstMAC = ethernetLayer.SrcMAC
	ethernetLayer.SrcMAC = ethMac

	ipSrc := ipLayer.SrcIP
	ipLayer.SrcIP = ipLayer.DstIP
	ipLayer.DstIP = ipSrc

	srcPort := udpLayer.SrcPort
	udpLayer.SrcPort = udpLayer.DstPort
	udpLayer.DstPort = srcPort
	err = udpLayer.SetNetworkLayerForChecksum(ipLayer)
	checkError(err)

	var answer layers.DNSResourceRecord
	answer.Type = layers.DNSTypeA
	answer.Class = layers.DNSClassIN
	answer.TTL = 200
	answer.IP = ipAddr

	dnsLayer.QR = true

	for _, q := range dnsLayer.Questions {
		if q.Type != layers.DNSTypeA || q.Class != layers.DNSClassIN {
			continue
		}

		answer.Name = q.Name

		dnsLayer.Answers = append(dnsLayer.Answers, answer)
		dnsLayer.ANCount = dnsLayer.ANCount + 1
	}

	buf := gopacket.NewSerializeBuffer()
	opts := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}

	err = gopacket.SerializeLayers(buf, opts, ethernetLayer, ipLayer, udpLayer, dnsLayer)
	checkError(err)

	return buf.Bytes()
}
开发者ID:razc411,项目名称:DNSMangler,代码行数:64,代码来源:main.go

示例4: NewTcpIpFlowFromPacket

// getPacketFlow returns a TcpIpFlow struct given a byte array packet
func NewTcpIpFlowFromPacket(packet []byte) (*TcpIpFlow, error) {
	var ip layers.IPv4
	var tcp layers.TCP
	decoded := []gopacket.LayerType{}
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &ip, &tcp)
	err := parser.DecodeLayers(packet, &decoded)
	if err != nil {
		return &TcpIpFlow{}, err
	}
	return &TcpIpFlow{
		ipFlow:  ip.NetworkFlow(),
		tcpFlow: tcp.TransportFlow(),
	}, nil
}
开发者ID:roger2000hk,项目名称:HoneyBadger,代码行数:15,代码来源:flow.go

示例5: serialize

func serialize(ipLayer *layers.IPv4) ([]byte, error) {
	/*Write the IPv4 header into a gopacket buffer*/
	buf := gopacket.NewSerializeBuffer()
	err := ipLayer.SerializeTo(buf, gopacket.SerializeOptions{FixLengths: false, ComputeChecksums: true})
	if err != nil {
		return nil, err
	}

	/*Write the gopacket buffer and the payload into a byte buffer, concatenating
	  the entire packet together.*/
	var buf2 bytes.Buffer
	buf2.Write(buf.Bytes())
	buf2.Write(ipLayer.Payload)

	return buf2.Bytes(), nil
}
开发者ID:ThomasJClark,项目名称:cs4516project,代码行数:16,代码来源:util.go

示例6: TestnotFrag

func TestnotFrag(t *testing.T) {
	ip := layers.IPv4{
		Version: 4,
		TTL:     220,
		SrcIP:   net.IPv4(1, 1, 1, 1),
		DstIP:   net.IPv4(2, 2, 2, 2),
		Flags:   layers.IPv4DontFragment,
	}
	v4defragger := ip4defrag.NewIPv4Defragmenter()
	b := gopacket.NewSerializeBuffer()
	ops := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}
	ip.SerializeTo(b, ops)
	pack := gopacket.NewPacket(b.Bytes(), layers.LinkTypeIPv4, gopacket.Default)
	_, err := v4defragger.DefragIPv4(pack.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
	if err != nil {
		t.Errorf("v4defrag do not return err when no frag pack is in")
	}
}
开发者ID:RunxiaWan,项目名称:PcapParser,代码行数:21,代码来源:main_test.go

示例7: benchmarkLayerDecode

func benchmarkLayerDecode(source *BufferPacketSource, assemble bool) {
	var tcp layers.TCP
	var ip layers.IPv4
	var eth layers.Ethernet
	var udp layers.UDP
	var icmp layers.ICMPv4
	var payload gopacket.Payload
	parser := gopacket.NewDecodingLayerParser(
		layers.LayerTypeEthernet,
		&eth, &ip, &icmp, &tcp, &udp, &payload)
	pool := tcpassembly.NewStreamPool(&streamFactory{})
	assembler := tcpassembly.NewAssembler(pool)
	var decoded []gopacket.LayerType
	start := time.Now()
	packets, decodedlayers, assembled := 0, 0, 0
	for {
		packets++
		data, ci, err := source.ReadPacketData()
		if err == io.EOF {
			break
		} else if err != nil {
			fmt.Println("Error reading packet: ", err)
			continue
		}
		err = parser.DecodeLayers(data, &decoded)
		for _, typ := range decoded {
			decodedlayers++
			if typ == layers.LayerTypeTCP && assemble {
				assembled++
				assembler.AssembleWithTimestamp(ip.NetworkFlow(), &tcp, ci.Timestamp)
			}
		}
	}
	if assemble {
		assembler.FlushAll()
	}
	duration := time.Since(start)
	fmt.Printf("\tRead in %d packets in %v, decoded %v layers, assembled %v packets: %v per packet\n", packets, duration, decodedlayers, assembled, duration/time.Duration(packets))
}
开发者ID:hgGeorg,项目名称:mongo,代码行数:39,代码来源:benchmark.go

示例8: TestnotFrag

func TestnotFrag(t *testing.T) {
	ip := layers.IPv4{
		Version: 4,
		TTL:     220,
		SrcIP:   net.IPv4(1, 1, 1, 1),
		DstIP:   net.IPv4(2, 2, 2, 2),
		Flags:   layers.IPv4DontFragment,
	}
	nomalPack := make(chan gopacket.Packet, 5)
	fragV4Pack := make(chan gopacket.Packet, 5)
	b := gopacket.NewSerializeBuffer()
	ops := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}
	ip.SerializeTo(b, ops)
	pack := gopacket.NewPacket(b.Bytes(), layers.LinkTypeIPv4, gopacket.Default)
	fragV4Pack <- pack
	err := v4Defrag(fragV4Pack, nomalPack)
	if err != nil {
		t.Errorf("v4defrag do not return err when no frag pack is in")
	}
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:23,代码来源:main_test.go

示例9: processor

// processor is a worker that decodes packets and passes on to Account and Log.
func (c *Capture) processor(num int, packetsCh <-chan gopacket.Packet) {
	log.Printf("processor %d: starting", num)

	buffer := c.nextBuffer()
	defer func() {
		// TODO: Save a checkpoint.
		if c.Log != nil {
			c.Log(buffer)
		}
	}()

	var (
		eth     layers.Ethernet
		ip4     layers.IPv4
		ip6     layers.IPv6
		tcp     layers.TCP
		udp     layers.UDP
		dns     layers.DNS
		payload gopacket.Payload
	)
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip4, &ip6, &tcp, &udp, &dns, &payload)
	for packet := range packetsCh {
		var decoded []gopacket.LayerType
		if err := parser.DecodeLayers(packet.Data(), &decoded); err != nil {
			log.Printf("processor %d: %v", num, err)
		}
		m := packet.Metadata()
		b := Metadata{
			Timestamp: m.Timestamp,
			Size:      uint64(m.Length),
		}
		for _, layerType := range decoded {
			switch layerType {
			case layers.LayerTypeIPv6:
				b.SrcIP, b.DstIP = ip6.SrcIP, ip6.DstIP
				b.SrcName, b.DstName = c.revDNS.names(local(b.SrcIP, b.DstIP), ip6.NetworkFlow())
				b.V6 = true
			case layers.LayerTypeIPv4:
				b.SrcIP, b.DstIP = ip4.SrcIP, ip4.DstIP
				b.SrcName, b.DstName = c.revDNS.names(local(b.SrcIP, b.DstIP), ip4.NetworkFlow())
			case layers.LayerTypeTCP:
				b.SrcPort, b.DstPort = uint16(tcp.SrcPort), uint16(tcp.DstPort)
			case layers.LayerTypeUDP:
				b.SrcPort, b.DstPort = uint16(udp.SrcPort), uint16(udp.DstPort)
			case layers.LayerTypeDNS:
				// Add DNS answers to reverse DNS map.
				// The "src" is the host who did the query, but answers are replies, so "src" = dst.
				// Should be here only after b.DstIP is set.
				c.revDNS.add(b.DstIP, &dns)
			}
		}

		c.Account(&b)

		if c.Log != nil {
			buffer = append(buffer, b)
			if len(buffer) >= c.BufferSize {
				go c.logBuffer(buffer)
				buffer = c.nextBuffer()
			}
		}
	}
	log.Printf("processor %d: stopping", num)
}
开发者ID:paulvalla,项目名称:caplog,代码行数:65,代码来源:packets.go

示例10: EvePayloadToPcap

// Given an EvePacket, convert the payload to a PCAP faking out the
// headers as best we can.
//
// A buffer containing the 1 packet pcap file will be returned.
func EvePayloadToPcap(event *EveEvent) ([]byte, error) {
	buffer := gopacket.NewSerializeBuffer()
	options := gopacket.SerializeOptions{
		FixLengths:       true,
		ComputeChecksums: true,
	}

	payloadLayer := gopacket.Payload(event.Payload.Bytes())
	payloadLayer.SerializeTo(buffer, options)

	srcIp := net.ParseIP(event.SrcIP)
	if srcIp == nil {
		return nil, fmt.Errorf("Failed to parse IP address %s.", event.SrcIP)
	}
	dstIp := net.ParseIP(event.DstIP)
	if dstIp == nil {
		return nil, fmt.Errorf("Failed to parse IP address %s.", event.DstIP)
	}

	proto, err := ProtoNumber(event.Proto)
	if err != nil {
		return nil, err
	}

	switch proto {
	case layers.IPProtocolTCP:
		// Could probably fake up a better TCP layer here.
		tcpLayer := layers.TCP{
			SrcPort: layers.TCPPort(event.SrcPort),
			DstPort: layers.TCPPort(event.DstPort),
		}
		tcpLayer.SerializeTo(buffer, options)
		break
	case layers.IPProtocolUDP:
		udpLayer := layers.UDP{
			SrcPort: layers.UDPPort(event.SrcPort),
			DstPort: layers.UDPPort(event.DstPort),
		}
		udpLayer.SerializeTo(buffer, options)
		break
	case layers.IPProtocolICMPv4:
		icmpLayer := layers.ICMPv4{
			TypeCode: layers.CreateICMPv4TypeCode(
				event.IcmpType, event.IcmpCode),
			Id:  0,
			Seq: 0,
		}
		icmpLayer.SerializeTo(buffer, options)
		break
	case layers.IPProtocolICMPv6:
		icmp6Layer := layers.ICMPv6{
			TypeCode: layers.CreateICMPv6TypeCode(
				event.IcmpType, event.IcmpCode),
		}
		icmp6Layer.SerializeTo(buffer, options)
		break
	default:
		return nil, fmt.Errorf("Unsupported protocol %d.", proto)
	}

	isIp6 := dstIp.To4() == nil

	if !isIp6 {
		ipLayer := layers.IPv4{
			SrcIP:    srcIp,
			DstIP:    dstIp,
			Version:  4,
			Protocol: proto,
			TTL:      64,
		}
		ipLayer.SerializeTo(buffer, options)
	} else {
		ip6Layer := layers.IPv6{
			Version: 6,
			SrcIP:   srcIp,
			DstIP:   dstIp,
		}
		ip6Layer.SerializeTo(buffer, options)
	}

	return pcap.CreatePcap(event.Timestamp.Time,
		buffer.Bytes(), layers.LinkTypeRaw)
}
开发者ID:jasonish,项目名称:evebox,代码行数:87,代码来源:eve.go

示例11: doCapture

//kick off packet procesing threads and start the packet capture loop
func doCapture(handle *pcap.Handle, logChan chan dnsLogEntry,
	config *pdnsConfig, reChan chan tcpDataStruct,
	stats *statsd.StatsdBuffer) {

	gcAgeDur, err := time.ParseDuration(config.gcAge)

	if err != nil {
		log.Fatal("Your gc_age parameter was not parseable.  Use a string like '-1m'")
	}

	gcIntervalDur, err := time.ParseDuration(config.gcInterval)

	if err != nil {
		log.Fatal("Your gc_age parameter was not parseable.  Use a string like '3m'")
	}

	//setup the global channel for reassembled TCP streams
	reassembleChan = reChan

	/* init channels for the packet handlers and kick off handler threads */
	var channels []chan *packetData
	for i := 0; i < config.numprocs; i++ {
		channels = append(channels, make(chan *packetData, 100))
	}

	for i := 0; i < config.numprocs; i++ {
		go handlePacket(channels[i], logChan, gcIntervalDur, gcAgeDur, i, stats)
	}

	// Use the handle as a packet source to process all packets
	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
	//only decode packet in response to function calls, this moves the
	//packet processing to the processing threads
	packetSource.DecodeOptions.Lazy = true
	//We don't mutate bytes of the packets, so no need to make a copy
	//this does mean we need to pass the packet via the channel, not a pointer to the packet
	//as the underlying buffer will get re-allocated
	packetSource.DecodeOptions.NoCopy = true

	/*
		parse up to the IP layer so we can consistently balance the packets across our
		processing threads

		TODO: in the future maybe pass this on the channel to so we don't reparse
				but the profiling I've done doesn't point to this as a problem
	*/

	var ethLayer layers.Ethernet
	var ipLayer layers.IPv4

	parser := gopacket.NewDecodingLayerParser(
		layers.LayerTypeEthernet,
		&ethLayer,
		&ipLayer,
	)

	foundLayerTypes := []gopacket.LayerType{}

CAPTURE:
	for {
		select {
		case reassembledTcp := <-reChan:
			pd := NewTcpData(reassembledTcp)
			channels[int(reassembledTcp.IpLayer.FastHash())&(config.numprocs-1)] <- pd
			if stats != nil {
				stats.Incr("reassembed_tcp", 1)
			}
		case packet := <-packetSource.Packets():
			if packet != nil {
				parser.DecodeLayers(packet.Data(), &foundLayerTypes)
				if foundLayerType(layers.LayerTypeIPv4, foundLayerTypes) {
					pd := NewPacketData(packet)
					channels[int(ipLayer.NetworkFlow().FastHash())&(config.numprocs-1)] <- pd
					if stats != nil {
						stats.Incr("packets", 1)
					}
				}
			} else {
				//if we get here, we're likely reading a pcap and we've finished
				//or, potentially, the physical device we've been reading from has been
				//downed.  Or something else crazy has gone wrong...so we break
				//out of the capture loop entirely.

				log.Debug("packetSource returned nil.")
				break CAPTURE
			}
		}
	}

	gracefulShutdown(channels, reChan, logChan)

}
开发者ID:Phillipmartin,项目名称:gopassivedns,代码行数:93,代码来源:main.go

示例12: NewTcpIpFlowFromLayers

// NewTcpIpFlowFromLayers given IPv4 and TCP layers it returns a TcpIpFlow
func NewTcpIpFlowFromLayers(ipLayer layers.IPv4, tcpLayer layers.TCP) *TcpIpFlow {
	return &TcpIpFlow{
		ipFlow:  ipLayer.NetworkFlow(),
		tcpFlow: tcpLayer.TransportFlow(),
	}
}
开发者ID:postfix,项目名称:SprayTrace,代码行数:7,代码来源:main.go

示例13: decodePackets

func (i *Filter) decodePackets() {
	var eth layers.Ethernet
	var ip layers.IPv4
	var ipv6 layers.IPv6
	var tcp layers.TCP
	var udp layers.UDP
	var payload gopacket.Payload
	anomalyTest := make(chan *Pan)
	alertChan := make(chan *AlertMessage)
	panClose := make(chan *PanCtl)

	//_, IPNet, err := net.ParseCIDR("10.240.0.0/16")
	_, IPNet, err := net.ParseCIDR(i.options.FilterIpCIDR)
	if err != nil {
		log.Errorf("Error parsing CIDR: %#v", err)
		i.Stop()
	}

	decodedLen := 6
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, &eth, &ip, &ipv6, &tcp, &udp, &payload)
	decoded := make([]gopacket.LayerType, 0, decodedLen)

	// Initialize wherefore goroutines
	piChan := PanopticonInfo()
	/*
		for at := 0; at < 10; at++ {
		}
	*/
	go i.AnomalyTester(anomalyTest, piChan, alertChan)
	go i.AlertSlack(alertChan)
	go i.PanRemover(panClose)

	for {
		select {
		case <-i.stopDecodeChan:
			return
		case timedRawPacket := <-i.decodePacketChan:
			newPayload := new(gopacket.Payload)
			payload = *newPayload
			err := parser.DecodeLayers(timedRawPacket.RawPacket, &decoded)
			if err != nil {
				continue
			}

			flow := types.NewTcpIpFlowFromFlows(ip.NetworkFlow(), tcp.TransportFlow())
			dcopy := make([]gopacket.LayerType, decodedLen, decodedLen)
			if dc := copy(dcopy, decoded); dc <= 0 {
				log.Errorf("Copy of decoded layers failed: %d", dc)
				continue
			}
			packetManifest := types.PacketManifest{
				Timestamp:     timedRawPacket.Timestamp,
				Flow:          flow,
				RawPacket:     timedRawPacket.RawPacket,
				DecodedLayers: dcopy,
				Eth:           eth,
				IP:            ip,
				IPv4:          ip,
				IPv6:          ipv6,
				TCP:           tcp,
				UDP:           udp,
				Payload:       payload,
			}

			//Short circut to only watch traffic heading in one direction
			//if FilterExternal(&packetManifest) == nil {
			if i.options.FilterSrc {
				if i.options.FilterBool && IPNet.Contains(packetManifest.IP.SrcIP) {
					continue
				}
			}

			if i.options.FilterDst {
				if i.options.FilterBool && IPNet.Contains(packetManifest.IP.DstIP) {
					continue
				}
			}

			//Pass packet manifest to the PM-Monitor function
			//TODO: Improve the flow around packet processing from the sniffer/splitter
			i.PMMonitor(&packetManifest, anomalyTest, panClose)

		}
	}
}
开发者ID:lytics,项目名称:wherefore,代码行数:85,代码来源:filter.go

示例14: main

func main() {
	defer util.Run()()
	var handle *pcap.Handle
	var err error

	flushDuration, err := time.ParseDuration(*flushAfter)
	if err != nil {
		log.Fatal("invalid flush duration: ", *flushAfter)
	}

	// log.Printf("starting capture on interface %q", *iface)
	// // Set up pcap packet capture
	// handle, err := pcap.OpenLive(*iface, int32(*snaplen), true, flushDuration/2)
	// if err != nil {
	// 	log.Fatal("error opening pcap handle: ", err)
	// }
	// Set up pcap packet capture
	if *fname != "" {
		log.Printf("Reading from pcap dump %q", *fname)
		handle, err = pcap.OpenOffline(*fname)
	} else {
		log.Fatalln("Error: pcap file name is required!")
		// log.Printf("Starting capture on interface %q", *iface)
		// handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever)
	}
	if err != nil {
		log.Fatal(err)
	}

	if err := handle.SetBPFFilter(*filter); err != nil {
		log.Fatal("error setting BPF filter: ", err)
	}

	// Set up assembly
	streamFactory := &statsStreamFactory{}
	streamPool := tcpassembly.NewStreamPool(streamFactory)
	assembler := tcpassembly.NewAssembler(streamPool)
	assembler.MaxBufferedPagesPerConnection = *bufferedPerConnection
	assembler.MaxBufferedPagesTotal = *bufferedTotal

	log.Println("reading in packets")

	// We use a DecodingLayerParser here instead of a simpler PacketSource.
	// This approach should be measurably faster, but is also more rigid.
	// PacketSource will handle any known type of packet safely and easily,
	// but DecodingLayerParser will only handle those packet types we
	// specifically pass in.  This trade-off can be quite useful, though, in
	// high-throughput situations.
	var eth layers.Ethernet
	var dot1q layers.Dot1Q
	var ip4 layers.IPv4
	var ip6 layers.IPv6
	var ip6extensions layers.IPv6ExtensionSkipper
	var tcp layers.TCP
	var payload gopacket.Payload
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet,
		&eth, &dot1q, &ip4, &ip6, &ip6extensions, &tcp, &payload)
	decoded := make([]gopacket.LayerType, 0, 4)

	nextFlush := time.Now().Add(flushDuration / 2)

	var byteCount int64
	start := time.Now()

loop:
	for ; *packetCount != 0; *packetCount-- {
		// Check to see if we should flush the streams we have
		// that haven't seen any new data in a while.  Note we set a
		// timeout on our PCAP handle, so this should happen even if we
		// never see packet data.
		if time.Now().After(nextFlush) {
			stats, _ := handle.Stats()
			log.Printf("flushing all streams that haven't seen packets in the last 2 minutes, pcap stats: %+v", stats)
			assembler.FlushOlderThan(time.Now().Add(flushDuration))
			nextFlush = time.Now().Add(flushDuration / 2)
		}

		// To speed things up, we're also using the ZeroCopy method for
		// reading packet data.  This method is faster than the normal
		// ReadPacketData, but the returned bytes in 'data' are
		// invalidated by any subsequent ZeroCopyReadPacketData call.
		// Note that tcpassembly is entirely compatible with this packet
		// reading method.  This is another trade-off which might be
		// appropriate for high-throughput sniffing:  it avoids a packet
		// copy, but its cost is much more careful handling of the
		// resulting byte slice.
		data, ci, err := handle.ZeroCopyReadPacketData()

		if err != nil {
			log.Printf("error getting packet: %v", err)
			break loop // continue
		}
		err = parser.DecodeLayers(data, &decoded)
		if err != nil {
			log.Printf("error decoding packet: %v", err)
			continue
		}
		if *logAllPackets {
			log.Printf("decoded the following layers: %v", decoded)
		}
//.........这里部分代码省略.........
开发者ID:cleesmith,项目名称:golang_learning,代码行数:101,代码来源:stats_assembly.go

示例15: setSiffFields

/* Adds the SIFF header to a packet, or modifies it in the case that it already
exists. Pass in the NFPacket, the flags (bitwise OR them if you need both), and
the capabilities and capability updates arrays. If only IsSiff is set, just fill
the last 4 bytes with dummy data, it'll be ignored. If you want to update specific
fields, then use the [update function name here] function */
func setSiffFields(packet *netfilter.NFPacket, flags uint8, capabilities []byte, updoots []byte) {
	var ipLayer *layers.IPv4
	var option [1]layers.IPv4Option
	option[0].OptionType = 86
	option[0].OptionLength = 8

	/* Get the IPv4 layer, and if it doesn't exist, keep doing shit
	   I can't be arsed for proper response outside the bounds of this project */
	if layer := packet.Packet.Layer(layers.LayerTypeIPv4); layer != nil {
		ipLayer = layer.(*layers.IPv4)
	} else {
		// maybe do something?
	}

	/* Modify the ip layer information */
	var IHLchange uint16 = uint16(ipLayer.IHL)

	// compute new IHL and length
	if (flags & CapabilityUpdate) == CapabilityUpdate {
		ipLayer.IHL = 8
		option[0].OptionLength = 12
	} else if (flags&IsSiff) == IsSiff || (flags&Exp) == Exp {
		ipLayer.IHL = 7
	} else {
		ipLayer.IHL = 5
	}

	IHLchange = uint16(ipLayer.IHL) - IHLchange
	if IHLchange != 0 {
		ipLayer.Length += IHLchange * 4
	}

	if (flags & Evil) == Evil {
		// set the evil flag. If we do this, we don't need to do anything else,
		// since evil packets are legacy, and don't have other flags
		ipLayer.Flags |= layers.IPv4EvilBit
	} else {
		// set the flags option
		option[0].OptionData = []byte{0, 0}
		if (flags & Exp) == Exp {
			option[0].OptionData[0] = byte(Exp)
		}
		if (flags & CapabilityUpdate) == CapabilityUpdate {
			option[0].OptionData[0] |= byte(IsSiff | CapabilityUpdate)
		} else if (flags & IsSiff) == IsSiff {
			option[0].OptionData[0] |= byte(IsSiff)
		}

		// handle the options
		if flags != 0 {
			for _, b := range capabilities {
				option[0].OptionData = append(option[0].OptionData, b)
			}
		}

		if (flags & CapabilityUpdate) == CapabilityUpdate {
			for _, b := range updoots {
				option[0].OptionData = append(option[0].OptionData, b)
			}
		}
		// add options
		if flags != 0 {
			ipLayer.Options = append([]layers.IPv4Option{option[0]}, ipLayer.Options...)
		}
	}

	// we're done
}
开发者ID:ThomasJClark,项目名称:cs4516project,代码行数:73,代码来源:siff-header.go


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