本文整理汇总了Golang中github.com/google/gopacket.Packet类的典型用法代码示例。如果您正苦于以下问题:Golang Packet类的具体用法?Golang Packet怎么用?Golang Packet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Packet类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
}
}
}
开发者ID:CNDonny,项目名称:scope,代码行数:28,代码来源:arpscan.go
示例2: HandlePacketTmp
// HandlePacketTmp used in development to display package data
func (krb *krbAuth) HandlePacketTmp(packet gopacket.Packet) {
app := packet.ApplicationLayer()
if app == nil {
return
}
udp := packet.TransportLayer().(*layers.UDP)
if udp.DstPort == 88 {
msgType := app.Payload()[17:18]
if msgType[0] == 10 { // AS-REQ type = 10
var n kdcReq
_, err := asn1.UnmarshalWithParams(app.Payload(), &n, asReqParam)
if err != nil {
fmt.Println("Error in asn.1 parse")
fmt.Println(err)
} else {
fmt.Println("-------------------------------")
fmt.Printf("PnDataType: %v\n", n.PnData[0].PnDataType)
//fmt.Println(hex.Dump(n.Pdata[0].PdataValue))
var encData encryptedData
asn1.Unmarshal(n.PnData[0].PnDataValue, &encData)
fmt.Printf("Etype: %v\n", encData.Etype)
fmt.Printf("Kvno: %v\n", encData.Kvno)
//fmt.Println(hex.Dump(encData.Cipher))
//fmt.Println(len(encData.Cipher))
fmt.Printf("Cname: %v\n", n.ReqBody.Cname)
fmt.Printf("Sname %v\n", n.ReqBody.Sname)
fmt.Printf("Realm: %v\n", n.ReqBody.Realm)
}
}
}
}
开发者ID:chrjoh,项目名称:pcapparse,代码行数:34,代码来源:krb5.go
示例3: decodePacket
func (b *Benchmark) decodePacket(pkt gopacket.Packet) (key *FiveTuple, payload []byte) {
ipv4, ok := pkt.NetworkLayer().(*layers.IPv4)
if !ok {
return // Ignore packets that aren't IPv4
}
if ipv4.FragOffset != 0 || (ipv4.Flags&layers.IPv4MoreFragments) != 0 {
return // Ignore fragmented packets.
}
var stream FiveTuple
stream.protocol = ipv4.Protocol
stream.srcAddr = ipv4.SrcIP
stream.dstAddr = ipv4.DstIP
switch t := pkt.TransportLayer().(type) {
case *layers.TCP:
stream.srcPort = uint16(t.SrcPort)
stream.dstPort = uint16(t.DstPort)
return &stream, t.Payload
case *layers.UDP:
stream.srcPort = uint16(t.SrcPort)
stream.dstPort = uint16(t.DstPort)
return &stream, t.Payload
}
return
}
开发者ID:flier,项目名称:gohs,代码行数:31,代码来源:main.go
示例4: outputStream
//if it is the output stream from local machine
func outputStream(packet gopacket.Packet, Srcaddr *metrics.Address, Destaddr *metrics.Address) {
ishttp, httpcontent := detectHttp(packet)
if httpcontent != nil {
if glog.V(1) {
//glog.Info("the content of packet sent:", string(httpcontent))
}
}
if ishttp {
sendtime := time.Now()
//iphandler := packet.Layer(layers.LayerTypeIPv4)
reqdetail := string(packet.ApplicationLayer().LayerContents())
httpinstance := &metrics.HttpTransaction{
Srcip: Srcaddr.IP,
Srcport: Srcaddr.PORT,
Destip: Destaddr.IP,
Destport: Destaddr.PORT,
Timesend: sendtime,
Packetdetail: metrics.Packetdetail{Requestdetail: reqdetail, Responddetail: ""},
}
//put the httpinstance into a list
if glog.V(1) {
glog.Infof("store the instance:%v\n", httpinstance)
}
httpinstancelist.PushBack(httpinstance)
if glog.V(2) {
glog.Infof("the length of the list :", httpinstancelist.Len())
}
}
}
开发者ID:wangzhezhe,项目名称:cpmonitor,代码行数:32,代码来源:packetcollect.go
示例5: 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 ""
}
开发者ID:chrjoh,项目名称:pcapparse,代码行数:8,代码来源:util.go
示例6: 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
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:60,代码来源:defragv6.go
示例7: 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,
}
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:9,代码来源:defragv6.go
示例8: 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
}
开发者ID:phaxio,项目名称:filterpcap,代码行数:10,代码来源:filterer.go
示例9: getFlow
func (p *processor) getFlow(pkt gopacket.Packet) gopacket.Flow {
mu := moldudp64Layer(pkt)
//p.flowBufSrc.Reset()
//p.flowBufSrc.Write(pkt.NetworkLayer().NetworkFlow().Src().Raw())
//p.flowBufSrc.Write(pkt.TransportLayer().TransportFlow().Src().Raw())
//p.flowBufSrc.Write(mu.Flow().Src().Raw())
p.flowBufDst.Reset()
p.flowBufDst.Write(pkt.NetworkLayer().NetworkFlow().Dst().Raw())
p.flowBufDst.Write(pkt.TransportLayer().TransportFlow().Dst().Raw())
p.flowBufDst.Write(mu.Flow().Dst().Raw())
return gopacket.NewFlow(packet.EndpointCombinedSession, p.flowBufSrc.Bytes(), p.flowBufDst.Bytes())
}
开发者ID:ikravets,项目名称:ev,代码行数:12,代码来源:copying_processor.go
示例10: 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
}
开发者ID:influx6,项目名称:goproj,代码行数:13,代码来源:snifer.go
示例11: 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
}
开发者ID:influx6,项目名称:goproj,代码行数:13,代码来源:snifer.go
示例12: 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)
}
}
开发者ID:ev46,项目名称:DNA,代码行数:16,代码来源:scanner.go
示例13: detectHttp
//detect the http packet return the info
func detectHttp(packet gopacket.Packet) (bool, []byte) {
applicationLayer := packet.ApplicationLayer()
if applicationLayer != nil {
if strings.Contains(string(applicationLayer.Payload()), "HTTP") {
if glog.V(1) {
glog.Info("HTTP found!")
}
return true, applicationLayer.LayerContents()
} else {
return false, nil
}
} else {
return false, nil
}
}
开发者ID:wangzhezhe,项目名称:packetagent,代码行数:17,代码来源:packetcollect.go
示例14: printPacketInfo
func printPacketInfo(packet gopacket.Packet) {
applicationLayer := packet.ApplicationLayer()
if applicationLayer != nil {
buff := []byte(applicationLayer.Payload())
p := rfc3164.NewParser(buff)
err := p.Parse()
if err != nil {
fmt.Println("Error decoding Payload:", err)
}
fmt.Printf("%s", p.Dump()["content"])
}
if err := packet.ErrorLayer(); err != nil {
fmt.Println("Error decoding some part of the packet:", err)
}
}
开发者ID:ljagiello,项目名称:ntail,代码行数:16,代码来源:ntail.go
示例15: 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
}
开发者ID:RunxiaWan,项目名称:oganization,代码行数:45,代码来源:defragv6.go
示例16: HandlePacket
// HandlePacket extract the krb5 AS-Requests
func (krb *krbAuth) HandlePacket(packet gopacket.Packet) {
app := packet.ApplicationLayer()
if app == nil {
return
}
udp := packet.TransportLayer().(*layers.UDP)
if udp.DstPort == 88 {
var n kdcReq
_, err := asn1.UnmarshalWithParams(app.Payload(), &n, asReqParam)
if err != nil {
return
}
if n.MsgType == asRequestType {
krb.addKdcReq(n)
}
}
}
开发者ID:chrjoh,项目名称:pcapparse,代码行数:19,代码来源:krb5.go
示例17: onRecvPing
func onRecvPing(pkt gopacket.Packet, icmp *layers.ICMPv4, ci *gopacket.CaptureInfo) {
payload := icmp.Payload
if payload == nil || len(payload) <= 0 {
return
}
sendStamp := binary.LittleEndian.Uint64(payload)
if sendStamp < 1000000 {
return
}
delay := ci.Timestamp.UnixNano() - int64(sendStamp)
probeResult := &types.ProbeResult{}
probeResult.Src = pkt.NetworkLayer().NetworkFlow().Dst().Raw()
probeResult.Dest = pkt.NetworkLayer().NetworkFlow().Src().Raw()
probeResult.Delay = int(delay / 1000)
probeResult.Stamp = ci.Timestamp.Unix()
probeResult.Type = types.ProbeTypePing
db.InsertProbeResult(probeResult)
}
开发者ID:adoyee,项目名称:probe,代码行数:19,代码来源:ping.go
示例18: 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))
}
}
}
}
开发者ID:mikeflynn,项目名称:go-dash-button,代码行数:42,代码来源:sniffer.go
示例19: 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:hgGeorg,项目名称:mongo,代码行数:20,代码来源:base_test.go
示例20: 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
}
开发者ID:jamessanford,项目名称:rtmp-debug,代码行数:56,代码来源:main.go
注:本文中的github.com/google/gopacket.Packet类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论