|
|
@ -1,6 +1,7 @@
|
|
|
|
package libpcap
|
|
|
|
package libpcap
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
import (
|
|
|
|
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"fmt"
|
|
|
|
"github.com/google/gopacket"
|
|
|
|
"github.com/google/gopacket"
|
|
|
|
"github.com/google/gopacket/pcap"
|
|
|
|
"github.com/google/gopacket/pcap"
|
|
|
@ -12,12 +13,18 @@ type NetCatch struct {
|
|
|
|
sentence string
|
|
|
|
sentence string
|
|
|
|
fn func(gopacket.Packet)
|
|
|
|
fn func(gopacket.Packet)
|
|
|
|
*pcap.Handle
|
|
|
|
*pcap.Handle
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
|
|
|
|
stopFn context.CancelFunc
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func (n *NetCatch) SetRecall(fn func(p gopacket.Packet)) {
|
|
|
|
func (n *NetCatch) SetRecall(fn func(p gopacket.Packet)) {
|
|
|
|
n.fn = fn
|
|
|
|
n.fn = fn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func (n *NetCatch) Stop() {
|
|
|
|
|
|
|
|
n.stopFn()
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func FindAllDevs() ([]pcap.Interface, error) {
|
|
|
|
func FindAllDevs() ([]pcap.Interface, error) {
|
|
|
|
return pcap.FindAllDevs()
|
|
|
|
return pcap.FindAllDevs()
|
|
|
|
}
|
|
|
|
}
|
|
|
@ -45,6 +52,7 @@ func NewCatch(host string, sentence string) (*NetCatch, error) {
|
|
|
|
nc.host = host
|
|
|
|
nc.host = host
|
|
|
|
nc.eth = eth
|
|
|
|
nc.eth = eth
|
|
|
|
nc.sentence = sentence
|
|
|
|
nc.sentence = sentence
|
|
|
|
|
|
|
|
nc.ctx, nc.stopFn = context.WithCancel(context.Background())
|
|
|
|
return nc, nil
|
|
|
|
return nc, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
@ -68,10 +76,14 @@ func (n *NetCatch) Run() error {
|
|
|
|
return err
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
pks := gopacket.NewPacketSource(handle, handle.LinkType())
|
|
|
|
pks := gopacket.NewPacketSource(handle, handle.LinkType())
|
|
|
|
for packet := range pks.Packets() {
|
|
|
|
for {
|
|
|
|
|
|
|
|
select {
|
|
|
|
|
|
|
|
case packet := <-pks.Packets():
|
|
|
|
if n.fn != nil {
|
|
|
|
if n.fn != nil {
|
|
|
|
n.fn(packet)
|
|
|
|
n.fn(packet)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
case <-n.ctx.Done():
|
|
|
|
return nil
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|