本文整理汇总了Golang中github.com/google/gopacket/pcap.OpenOffline函数的典型用法代码示例。如果您正苦于以下问题:Golang OpenOffline函数的具体用法?Golang OpenOffline怎么用?Golang OpenOffline使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了OpenOffline函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: runTestZone
func runTestZone(){
fmt.Println("We're in test zone")
if handle, err := pcap.OpenOffline("/home/jnankin/Desktop/test.pcap"); err != nil {
panic(err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
if packet.Layer(layers.LayerTypeTCP) != nil {
appLayer := packet.ApplicationLayer()
fmt.Println("APP LAYER: \n" + string(appLayer.Payload()) + "\n\n");
sipMessage := sipparser.ParseMsg(string(appLayer.Payload()))
fmt.Println("SIP BODY: \n" + sipMessage.Body + "\n\n");
fmt.Println("Content length: \n" + sipMessage.ContentLength + "\n\n");
/*SIP PDU detection: 1st Line contains SIP/2.0
foreach line, if it's a content length, set it.
add each line to the current sip message
if the line is blank:
if I have a content length:
add content length more bytes from the message to the current sip message
add the current message to the list of messages found
if there are still messages in the buffer, the packet is fragmented and we need more messages
*/
}
}
}
}
示例2: NewPcapFileSniffer
func NewPcapFileSniffer(filename string) (*PcapHandle, error) {
pcapFileHandle, err := pcap.OpenOffline(filename)
pcapHandle := PcapHandle{
handle: pcapFileHandle,
}
return &pcapHandle, err
}
示例3: ParsingFinished
func (c *cmdBenchmark) ParsingFinished() (err error) {
if !c.shouldExecute {
return
}
handle, err := pcap.OpenOffline(c.InputFileName)
errs.CheckE(err)
defer handle.Close()
bo := packet.NewBufferedObtainer(handle)
var pp packet.Processor
if c.ProcCopy {
pp = processor.NewCopyingProcessor()
} else {
pp = processor.NewReusingProcessor()
}
pp.SetObtainer(bo)
var totalDuration time.Duration
for i := 0; i < c.Iter; i++ {
bo.Reset()
start := time.Now()
pp.ProcessAll()
duration := time.Since(start)
totalDuration += duration
}
timePerPacket := totalDuration / time.Duration(c.Iter*bo.Packets())
fmt.Printf("total duration: %s, time/pkt: %s\n", totalDuration, timePerPacket)
return
}
示例4: TestTCP
func TestTCP(t *testing.T) {
handle, err := pcap.OpenOffline("tcptest.pcap")
if err != nil {
panic(err)
}
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
defer handle.Close()
tcpPack := make(chan gopacket.Packet, 10)
nomalPack := make(chan gopacket.Packet, 5)
for input_pack := range packetSource.Packets() { // send tcp package for channel
tcpLayer := input_pack.Layer(layers.LayerTypeTCP)
if tcpLayer != nil {
tcpPack <- input_pack
// send packet to tcp ASSEMBLER
}
}
streamFactory := &DNSStreamFactory{normal: nomalPack}
streamPool := tcpassembly.NewStreamPool(streamFactory)
assembler := tcpassembly.NewAssembler(streamPool)
go tcpAssemble(tcpPack, assembler)
pack := <-nomalPack
udpLayer := pack.Layer(layers.LayerTypeUDP)
if udpLayer == nil {
t.Errorf("can not fine udp Layer in result")
}
dns_message := new(dns.Msg)
err = dns_message.Unpack(udpLayer.LayerPayload())
if err != nil {
t.Errorf("can not parse dns message")
}
fmt.Printf(dns_message.String())
}
示例5: packetSource
func packetSource() *gopacket.PacketSource {
if *inputPcap != "" {
handle, err := pcap.OpenOffline(*inputPcap)
if err != nil {
log.Fatalln(err)
}
fmt.Printf("open pcap file \"%s\"\n", *inputPcap)
return gopacket.NewPacketSource(handle, handle.LinkType())
}
if *device == "" {
*device = autoSelectDev()
if *device == "" {
log.Fatalln("no device to capture")
}
}
handle, err := pcap.OpenLive(*device, 1024*1024, true, pcap.BlockForever)
if err != nil {
log.Fatalln(err)
}
if *bpf != "" {
if err = handle.SetBPFFilter(*bpf); err != nil {
log.Fatalln("Failed to set BPF filter:", err)
}
}
fmt.Printf("open live on device \"%s\", bpf \"%s\", serves on port %d\n", *device, *bpf, *bindingPort)
return gopacket.NewPacketSource(handle, handle.LinkType())
}
示例6: main
func main() {
flag.Parse()
pcap, err := pcap.OpenOffline(*pcapFile)
if err != nil {
fmt.Fprintln(os.Stderr, "error opening pcap file:", err)
os.Exit(1)
}
h := mongocaputils.NewPacketHandler(pcap)
m := mongocaputils.NewMongoOpStream(*packetBufSize)
ch := make(chan struct{})
go func() {
defer close(ch)
for op := range m.Ops {
if _, ok := op.Op.(*mongoproto.OpUnknown); !ok {
fmt.Printf("%f %v\n", float64(op.Seen.Sub(m.FirstSeen))/10e8, op)
}
}
}()
if err := h.Handle(m, -1); err != nil {
fmt.Fprintln(os.Stderr, "mongocapcat: error handling packet stream:", err)
}
<-ch
}
示例7: TestNgnet
func TestNgnet(t *testing.T) {
eventChan := make(chan interface{}, 1024)
f := NewHttpStreamFactory(eventChan)
pool := tcpassembly.NewStreamPool(f)
assembler := tcpassembly.NewAssembler(pool)
packetCount := 0
fmt.Println("Run")
if handle, err := pcap.OpenOffline("dump.pcapng"); err != nil {
panic(err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
net_layer := packet.NetworkLayer()
trans_layer := packet.TransportLayer()
if net_layer == nil {
continue
}
if trans_layer == nil {
continue
}
packetCount++
tcp, _ := trans_layer.(*layers.TCP)
assembler.AssembleWithTimestamp(net_layer.NetworkFlow(), tcp, packet.Metadata().CaptureInfo.Timestamp)
}
}
assembler.FlushAll()
f.Wait()
fmt.Println("packet:", packetCount, "http:", len(eventChan))
}
示例8: ProcessPackets
func ProcessPackets(pcapFile string,
mongodHost string,
mongodPort string) {
if handle, err := pcap.OpenOffline(pcapFile); err != nil {
panic(err)
} else {
var connectionWaitGroup sync.WaitGroup
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
firstPacket := <-packetSource.Packets()
packetMinTimestamp = GetPacketTime(firstPacket)
mapHostConnection = make(map[string]*MongoConnection)
SendPacket(firstPacket,
&connectionWaitGroup,
mongodHost,
mongodPort)
for packet := range packetSource.Packets() {
SendPacket(packet,
&connectionWaitGroup,
mongodHost,
mongodPort)
}
for _, mConnection := range mapHostConnection {
mConnection.EOF()
}
connectionWaitGroup.Wait()
}
}
示例9: init
//init re-initializes a snifer for uses
func (s *Snifer) init() error {
var handle *pcap.Handle
var err error
if s.conf.Offline {
handle, err = pcap.OpenOffline(s.source)
checkError(err, fmt.Sprintf("Create offline handle %s", s.source))
} else {
handle, err = pcap.OpenLive(s.source, s.conf.MaxPacket, s.conf.Promod, s.conf.Timeout)
checkError(err, fmt.Sprintf("Create Live handle %s", s.source))
if err == nil {
err = handle.SetBPFFilter(s.conf.Filter)
checkError(err, fmt.Sprintf("Setting BPFFilter %s: %s", s.source, s.conf.Filter))
}
}
if err != nil {
checkError(err, fmt.Sprintf("Creating Snifer for %s", s.source))
return err
}
s.handle = handle
log.Printf("Snifer: Handler created and ready!")
return nil
}
示例10: pcapInfo
func pcapInfo(filename string) (start time.Time, end time.Time, packets int, size int) {
handleRead, err := pcap.OpenOffline(*fname)
if err != nil {
log.Fatal("PCAP OpenOffline error (handle to read packet):", err)
}
var previousTs time.Time
var deltaTotal time.Duration
for {
data, ci, err := handleRead.ReadPacketData()
if err != nil && err != io.EOF {
log.Fatal(err)
} else if err == io.EOF {
break
} else {
if start.IsZero() {
start = ci.Timestamp
}
end = ci.Timestamp
packets++
size += len(data)
if previousTs.IsZero() {
previousTs = ci.Timestamp
} else {
deltaTotal += ci.Timestamp.Sub(previousTs)
previousTs = ci.Timestamp
}
}
}
fmt.Printf("Avg packet rate %d/s\n", packets/int(deltaTotal.Seconds()))
return start, end, packets, size
}
示例11: main
func main() {
flag.Parse()
var handle *pcap.Handle
var err error
if *fname != "" {
log.Printf("Reading from pcap dump %q", *fname)
handle, err = pcap.OpenOffline(*fname)
} else {
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(err)
}
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
if packet == nil {
return
}
if udpLayer := packet.Layer(layers.LayerTypeUDP); udpLayer != nil {
udp, _ := udpLayer.(*layers.UDP)
fwdSIPPacket(udp.BaseLayer.Payload)
}
}
}
示例12: main
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s pcap\n", os.Args[0])
os.Exit(0)
}
input, output := os.Args[1], "out.ts"
handle, err := pcap.OpenOffline(input)
if err != nil {
log.Fatal(err)
}
defer handle.Close()
f, err := os.Create(output)
if err != nil {
log.Fatal(err)
}
defer f.Close()
source := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range source.Packets() {
appLayer := packet.ApplicationLayer()
if appLayer != nil {
payload := appLayer.Payload()
if len(payload) == UDPSize {
f.Write(payload)
} else if len(payload) == HRTPSize {
offset := HRTPSize - UDPSize
f.Write(payload[offset:HRTPSize])
}
}
}
}
示例13: getOpstream
func getOpstream(cfg OpStreamSettings) (*packetHandlerContext, error) {
if cfg.PacketBufSize < 1 {
return nil, fmt.Errorf("invalid packet buffer size")
}
var pcapHandle *pcap.Handle
var err error
if len(cfg.PcapFile) > 0 {
pcapHandle, err = pcap.OpenOffline(cfg.PcapFile)
if err != nil {
return nil, fmt.Errorf("error opening pcap file: %v", err)
}
} else if len(cfg.NetworkInterface) > 0 {
pcapHandle, err = pcap.OpenLive(cfg.NetworkInterface, 32*1024*1024, false, pcap.BlockForever)
if err != nil {
return nil, fmt.Errorf("error listening to network interface: %v", err)
}
} else {
return nil, fmt.Errorf("must specify either a pcap file or network interface to record from")
}
if len(cfg.Expression) > 0 {
err = pcapHandle.SetBPFFilter(cfg.Expression)
if err != nil {
return nil, fmt.Errorf("error setting packet filter expression: %v", err)
}
}
h := NewPacketHandler(pcapHandle)
h.Verbose = userInfoLogger.isInVerbosity(DebugLow)
toolDebugLogger.Logvf(Info, "Created packet buffer size %d", cfg.PacketBufSize)
m := NewMongoOpStream(cfg.PacketBufSize)
return &packetHandlerContext{h, m, pcapHandle}, nil
}
示例14: openFile
func openFile(pcapFile string) *pcap.Handle {
handle, err := pcap.OpenOffline(pcapFile)
if err != nil {
log.Fatal("Open file", pcapFile, "error:", err)
}
return handle
}
示例15: main
func main() {
defer util.Run()()
var handle *pcap.Handle
var err error
// 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(err)
}
// Set up assembly
streamFactory := &httpStreamFactory{}
streamPool := tcpassembly.NewStreamPool(streamFactory)
assembler := tcpassembly.NewAssembler(streamPool)
log.Println("reading in packets")
// Read in packets, pass to assembler.
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
packets := packetSource.Packets()
ticker := time.Tick(time.Minute)
for {
select {
case packet := <-packets:
// A nil packet indicates the end of a pcap file.
if packet == nil {
return
}
if *logAllPackets {
log.Println("\npacket:")
// log.Println(packet)
}
if packet.NetworkLayer() == nil || packet.TransportLayer() == nil || packet.TransportLayer().LayerType() != layers.LayerTypeTCP {
log.Println("Unusable packet")
continue
}
tcp := packet.TransportLayer().(*layers.TCP)
log.Printf("\n.......................................................\n")
log.Printf("packet:\n")
log.Printf("packet.Metadata().Timestamp=%T=%v=%v:\n%#v\n", packet.Metadata().Timestamp, packet.Metadata().Timestamp, packet.Metadata().Timestamp.UTC(), packet.Metadata().Timestamp)
assembler.AssembleWithTimestamp(packet.NetworkLayer().NetworkFlow(), tcp, packet.Metadata().Timestamp)
case <-ticker:
// Every minute, flush connections that haven't seen activity in the past 2 minutes.
assembler.FlushOlderThan(time.Now().Add(time.Minute * -2))
}
}
}