本文整理匯總了Golang中github.com/google/gopacket.Packet.Layer方法的典型用法代碼示例。如果您正苦於以下問題:Golang Packet.Layer方法的具體用法?Golang Packet.Layer怎麽用?Golang Packet.Layer使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/google/gopacket.Packet
的用法示例。
在下文中一共展示了Packet.Layer方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: 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))
}
}
}
示例2: handlePacket
func handlePacket(packet gopacket.Packet) {
// Get the TCP layer from this packet
tcpLayer := packet.Layer(layers.LayerTypeTCP)
if tcpLayer != nil {
// Get actual TCP data from this layer
tcp, _ := tcpLayer.(*layers.TCP)
fmt.Printf("From: src port %6d\tTo: dst port %6d\t", tcp.SrcPort, tcp.DstPort)
fmt.Printf("Ack: %12v\t", tcp.Ack)
}
// Iterate over all layers, printing out each layer type
for _, layer := range packet.Layers() {
layerType := layer.LayerType()
fmt.Printf("%8v %5v", layerType, len(layer.LayerPayload()))
}
applicationLayer := packet.ApplicationLayer()
if applicationLayer != nil {
fmt.Println("Application layer/Payload found.")
//fmt.Printf("%s\n", applicationLayer.Payload())
}
fmt.Println("")
}
示例3: GetDstIP
// GetDstIP returns the destination ipV4§ as a string
func GetDstIP(packet gopacket.Packet) string {
if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {
ip, _ := ipLayer.(*layers.IPv4)
return ip.DstIP.String()
}
return ""
}
示例4: build
//need work
func (f *fragmentList) build(in gopacket.Packet) (gopacket.Packet, error) {
var final []byte
var currentOffset uint16 = 0
debug.Printf("defrag: building the datagram \n")
for e := f.List.Front(); e != nil; e = e.Next() {
pack, _ := e.Value.(gopacket.Packet)
frag := pack.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
ip := pack.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
if frag.FragmentOffset*8 == currentOffset {
debug.Printf("defrag: building - adding %d\n", frag.FragmentOffset*8)
final = append(final, frag.Payload...)
currentOffset = currentOffset + ip.Length - 8
} else if frag.FragmentOffset*8 < currentOffset {
// overlapping fragment - let's take only what we need
startAt := currentOffset - frag.FragmentOffset*8
debug.Printf("defrag: building - overlapping, starting at %d\n",
startAt)
if startAt > ip.Length-8 {
return nil, fmt.Errorf("defrag: building - invalid fragment")
}
final = append(final, frag.Payload[startAt:]...)
currentOffset = currentOffset + frag.FragmentOffset*8
} else {
// Houston - we have an hole !
debug.Printf("defrag: hole found while building, " +
"stopping the defrag process\n")
return nil, fmt.Errorf("defrag: building - hole found")
}
debug.Printf("defrag: building - next is %d\n", currentOffset)
}
final_ipv6 := in.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
final_frag := in.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
// TODO recompute IP Checksum
out := &layers.IPv6{
Version: final_ipv6.Version,
TrafficClass: final_ipv6.TrafficClass,
FlowLabel: final_ipv6.FlowLabel,
Length: f.Highest,
NextHeader: final_frag.NextHeader,
HopLimit: final_ipv6.HopLimit,
SrcIP: final_ipv6.SrcIP,
DstIP: final_ipv6.DstIP,
HopByHop: final_ipv6.HopByHop,
}
out.Payload = final
v6SerailizeBuffer := gopacket.NewSerializeBuffer()
v6Buffer, _ := v6SerailizeBuffer.PrependBytes(len(final))
copy(v6Buffer, final)
ops := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
out.SerializeTo(v6SerailizeBuffer, ops)
outPacket := gopacket.NewPacket(v6SerailizeBuffer.Bytes(), layers.LayerTypeIPv6, gopacket.Default)
outPacket.Metadata().CaptureLength = len(outPacket.Data())
outPacket.Metadata().Length = len(outPacket.Data())
return outPacket, nil
}
示例5: newipv6
// newIPv4 returns a new initialized IPv4 Flow
func newipv6(packet gopacket.Packet) ipv6 {
frag := packet.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
ip := packet.Layer(layers.LayerTypeIPv6).(*layers.IPv6)
return ipv6{
ip6: ip.NetworkFlow(),
id: frag.Identification,
}
}
示例6: main
func main() {
flag.Usage = usage
flag.Parse()
pcapfile, err := openPcap()
if err != nil {
glog.Fatalf("%v", err)
}
bpf := strings.Join(flag.Args(), " ")
if err = pcapfile.SetBPFFilter(bpf); err != nil {
glog.Fatalf("unable to set BPF: %v", err)
}
// "Pass this stream factory to an tcpassembly.StreamPool ,
// start up an tcpassembly.Assembler, and you're good to go!"
done := make(chan struct{})
results := make(chan string)
go printResults(done, results)
wg := &sync.WaitGroup{}
rtmp := &rtmpStreamWrapper{wg, results}
pool := tcpassembly.NewStreamPool(rtmp)
asm := tcpassembly.NewAssembler(pool)
asm.MaxBufferedPagesTotal = 4096 // limit gopacket memory allocation
source := gopacket.NewPacketSource(pcapfile, pcapfile.LinkType())
var pkt gopacket.Packet
for {
pkt, err = source.NextPacket()
if pkt == nil || err != nil {
break
}
if tcp := pkt.Layer(layers.LayerTypeTCP); tcp != nil {
asm.AssembleWithTimestamp(
pkt.TransportLayer().TransportFlow(),
tcp.(*layers.TCP),
pkt.Metadata().Timestamp)
}
}
if err != nil && !errIsEOF(err) {
glog.Errorf("packet: %v", err)
if err = pcapfile.Error(); err != nil {
glog.Errorf("pcap: %v", err)
}
}
asm.FlushAll() // abort any in progress tcp connections
wg.Wait() // tcp streams have finished processing
close(results) // no more results will be generated by tcp streams
<-done // printResults has finished
}
示例7: parseForSip
func parseForSip(packet gopacket.Packet) *sipparser.SipMsg {
ipLayer := packet.Layer(layers.LayerTypeIPv4)
appLayer := packet.ApplicationLayer()
fmt.Println("PAYLOAD: " + string(appLayer.Payload()) + " - END.")
if ipLayer != nil && appLayer != nil && strings.Contains(string(appLayer.Payload()), "SIP") {
return sipparser.ParseMsg(string(appLayer.Payload()))
}
return nil
}
示例8: RetrieveSrcPort
//RetrieveSrcPort retrieves the src port of a packet
func RetrieveSrcPort(packet gopacket.Packet) (int, error) {
iplayers := packet.Layer(layers.LayerTypeTCP)
if iplayers != nil {
ipc, ok := iplayers.(*layers.TCP)
if ok {
return int(ipc.SrcPort), nil
}
}
return 0, ErrBadPacket
}
示例9: RetrieveSrcIP
//RetrieveSrcIP retrieves the src ip of a packet
func RetrieveSrcIP(packet gopacket.Packet) (net.IP, error) {
iplayers := packet.Layer(layers.LayerTypeIPv4)
if iplayers != nil {
ipc, ok := iplayers.(*layers.IPv4)
if ok {
return ipc.SrcIP, nil
}
}
return nil, ErrBadPacket
}
示例10: process_gopacket
//------ PCAP Print PCAP Data -----
func process_gopacket(packet gopacket.Packet) {
// Let's see if the packet is IP (even though the ether type told us)
ipLayer := packet.Layer(layers.LayerTypeIPv4)
if ipLayer != nil {
ip, _ := ipLayer.(*layers.IPv4)
register_network_call_with_redis(ip.Protocol, ip.DstIP)
}
// Check for errors
if err := packet.ErrorLayer(); err != nil {
fmt.Println("Error decoding some part of the packet:", err)
}
}
示例11: DefragIPv6
func (d *IPv6Defragmenter) DefragIPv6(in gopacket.Packet) (gopacket.Packet, error) {
// check if we need to defrag
frag := in.Layer(layers.LayerTypeIPv6Fragment)
if frag == nil {
return in, nil
}
v6frag := frag.(*layers.IPv6Fragment)
// ok, got a fragment
debug.Printf("defrag: got in.Id=%d in.FragOffset=%d",
v6frag.Identification, v6frag.FragmentOffset*8)
// do we already has seen a flow between src/dst with that Id
ipf := newipv6(in)
var fl *fragmentList
var exist bool
d.Lock()
fl, exist = d.ipFlows[ipf]
if !exist {
debug.Printf("defrag: creating a new flow\n")
fl = new(fragmentList)
d.ipFlows[ipf] = fl
}
d.Unlock()
// insert, and if final build it
out, err2 := fl.insert(in)
// at last, if we hit the maximum frag list len
// without any defrag success, we just drop everything and
// raise an error
if out == nil && fl.List.Len()+1 > IPv6MaximumFragmentListLen {
d.Lock()
fl = new(fragmentList)
d.ipFlows[ipf] = fl
d.Unlock()
return nil, fmt.Errorf("defrag: Fragment List hits its maximum"+
"size(%d), without sucess. Flushing the list",
IPv6MaximumFragmentListLen)
}
// if we got a packet, it's a new one, and he is defragmented
if out != nil {
return out, nil
}
return nil, err2
}
示例12: insert
func (f *fragmentList) insert(in gopacket.Packet) (gopacket.Packet, error) {
// TODO: should keep a copy of *in in the list
// or not (ie the packet source is reliable) ?
fragv6 := in.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
fragOffset := fragv6.FragmentOffset * 8
if fragOffset >= f.Highest {
f.List.PushBack(in)
} else {
for e := f.List.Front(); e != nil; e = e.Next() {
packet, _ := e.Value.(gopacket.Packet)
frag := packet.Layer(layers.LayerTypeIPv6Fragment).(*layers.IPv6Fragment)
if fragv6.FragmentOffset <= frag.FragmentOffset {
debug.Printf("defrag: inserting frag %d before existing frag %d \n",
fragOffset, frag.FragmentOffset*8)
f.List.InsertBefore(in, e)
break
}
}
}
// packet.Metadata().Timestamp should have been better, but
// we don't have this info there...
f.LastSeen = in.Metadata().Timestamp
fragLength := in.Layer(layers.LayerTypeIPv6).(*layers.IPv6).Length - 8 // need to conform
// After inserting the Fragment, we update the counters
if f.Highest < fragOffset+fragLength {
f.Highest = fragOffset + fragLength
}
f.Current = f.Current + fragLength
debug.Printf("defrag: insert ListLen: %d Highest:%d Current:%d\n",
f.List.Len(),
f.Highest, f.Current)
// Final Fragment ?
if fragv6.MoreFragments == false {
f.FinalReceived = true
}
// Ready to try defrag ?
if f.FinalReceived && f.Highest == f.Current {
return f.build(in)
}
return nil, nil
}
示例13: readARP
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 !net.IP(arp.SourceProtAddress).Equal(net.ParseIP("0.0.0.0")) {
continue
}
found := false
for mac, fn := range DashMacs {
if net.HardwareAddr(arp.SourceHwAddress).String() == mac {
if !State[mac] {
log.Printf("Click sniffed for %v", mac)
State[mac] = true
fn()
State[mac] = false
}
found = true
}
}
if !found {
log.Printf("FOUND UNKNOWN MAC: %v", net.HardwareAddr(arp.SourceHwAddress))
}
}
}
}
示例14: handlePacket
func (this *Sniff) handlePacket(packet gopacket.Packet) {
ipLayer := packet.Layer(layers.LayerTypeIPv4)
if ipLayer == nil {
return
}
ip, _ := ipLayer.(*layers.IPv4)
tcpLayer := packet.Layer(layers.LayerTypeTCP)
if tcpLayer == nil {
return
}
tcp, _ := tcpLayer.(*layers.TCP)
applicationLayer := packet.ApplicationLayer()
if applicationLayer == nil {
return
}
this.Ui.Info(fmt.Sprintf("%s:%s -> %s:%s %dB", ip.SrcIP, tcp.SrcPort, ip.DstIP, tcp.DstPort, len(applicationLayer.Payload())))
this.Ui.Output(fmt.Sprintf("%s", string(applicationLayer.Payload())))
}
示例15: processPacketInfo
//every time get a new packet
func processPacketInfo(packet gopacket.Packet) {
//get the specified layer
tcpLayer := packet.Layer(layers.LayerTypeTCP)
if tcpLayer != nil {
if glog.V(2) {
glog.Info("TCP layer is detected.")
}
tcphandler, _ := tcpLayer.(*layers.TCP)
srcport := tcphandler.SrcPort
destport := tcphandler.DstPort
//get the specified layer
iplayer := packet.Layer(layers.LayerTypeIPv4)
httphandler, _ := iplayer.(*layers.IPv4)
srcip := httphandler.SrcIP
destip := httphandler.DstIP
//log.Println(srcip.String())
//send the packet from local machine
Srcaddr := &Address{IP: srcip.String(), PORT: srcport.String()}
Destaddr := &Address{IP: destip.String(), PORT: destport.String()}
if glog.V(2) {
glog.Infof("srcaddr %v destaddr %v \n", Srcaddr, Destaddr)
}
var mutex = &sync.Mutex{}
if srcip.String() == localip {
mutex.Lock()
outputStream(packet, Srcaddr, Destaddr)
mutex.Unlock()
}
//get the packet from the local machine
if destip.String() == localip {
mutex.Lock()
inputStream(packet, Srcaddr, Destaddr)
mutex.Unlock()
}
}
}