本文整理汇总了Golang中github.com/google/gopacket.NewPacket函数的典型用法代码示例。如果您正苦于以下问题:Golang NewPacket函数的具体用法?Golang NewPacket怎么用?Golang NewPacket使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewPacket函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Testv4Defrag
func Testv4Defrag(t *testing.T) {
nomalPack := make(chan gopacket.Packet, 5)
fragV4Pack := make(chan gopacket.Packet, 5)
go v4Defrag(fragV4Pack, nomalPack)
pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
fragV4Pack <- pack1
pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
fragV4Pack <- pack2
pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
fragV4Pack <- pack3
pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
fragV4Pack <- pack4
result := <-nomalPack
ip := result.Layer(layers.LayerTypeIPv4)
//TEST if the ip matches expectation
if ip == nil {
t.Errorf("defrag does not return IPV4 LAYER")
}
if len(ip.LayerPayload()) != 4508 {
t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
}
validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
validPayload = append(validPayload, testPing1Frag3[34:]...)
validPayload = append(validPayload, testPing1Frag4[34:]...)
if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
fmt.Println(bytediff.BashOutput.String(
bytediff.Diff(validPayload, ip.LayerPayload())))
t.Errorf("defrag: payload is not correctly defragmented")
}
}
示例2: TestUDPPacketVXLANGetInnerEthernetLayer
func TestUDPPacketVXLANGetInnerEthernetLayer(t *testing.T) {
p := gopacket.NewPacket(testUDPPacketVXLAN, LinkTypeEthernet, gopacket.Default)
if p.ErrorLayer() != nil {
t.Error("Failed to decode packet:", p.ErrorLayer().Error())
}
// show how to extract the inner ethernet header
vxlan := p.Layer(LayerTypeVxlan)
p2 := gopacket.NewPacket(vxlan.LayerPayload(), LinkTypeEthernet, gopacket.Default)
ethernetL := p2.Layer(LayerTypeEthernet)
ethernet, _ := ethernetL.(*Ethernet)
if ethernet == nil {
t.Error("Failed to find ethernet header")
}
dstmac := net.HardwareAddr{0x00, 0x30, 0x88, 0x01, 0x00, 0x02}
srcmac := net.HardwareAddr{0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04}
if ethernet.DstMAC[0] != dstmac[0] &&
ethernet.DstMAC[1] != dstmac[1] &&
ethernet.DstMAC[2] != dstmac[2] &&
ethernet.DstMAC[3] != dstmac[3] &&
ethernet.DstMAC[4] != dstmac[4] &&
ethernet.DstMAC[5] != dstmac[5] &&
ethernet.SrcMAC[0] != srcmac[0] &&
ethernet.SrcMAC[1] != srcmac[1] &&
ethernet.SrcMAC[2] != srcmac[2] &&
ethernet.SrcMAC[3] != srcmac[3] &&
ethernet.SrcMAC[4] != srcmac[4] &&
ethernet.SrcMAC[5] != srcmac[5] &&
ethernet.EthernetType != 0x0800 {
t.Error("Decoded packet incorrect values")
}
}
示例3: main
func main() {
// If we don't have a handle to a device or a file, but we have a bunch
// of raw bytes, we can try to decode them in to packet information
// NewPacket() takes the raw bytes that make up the packet as the first parameter
// The second parameter is the lowest level layer you want to decode. It will
// decode that layer and all layers on top of it. The third layer
// is the type of decoding: default(all at once), lazy(on demand), and NoCopy
// which will not create a copy of the buffer
// Create an packet with ethernet, IP, TCP, and payload layers
// We are creating one we know will be decoded properly but
// your byte source could be anything. If any of the packets
// come back as nil, that means it could not decode it in to
// the proper layer (malformed or incorrect packet type)
payload := []byte{2, 4, 6}
options := gopacket.SerializeOptions{}
buffer := gopacket.NewSerializeBuffer()
gopacket.SerializeLayers(buffer, options,
&layers.Ethernet{},
&layers.IPv4{},
&layers.TCP{},
gopacket.Payload(payload),
)
rawBytes := buffer.Bytes()
// Decode an ethernet packet
ethPacket :=
gopacket.NewPacket(
rawBytes,
layers.LayerTypeEthernet,
gopacket.Default,
)
// with Lazy decoding it will only decode what it needs when it needs it
// This is not concurrency safe. If using concurrency, use default
ipPacket :=
gopacket.NewPacket(
rawBytes,
layers.LayerTypeIPv4,
gopacket.Lazy,
)
// With the NoCopy option, the underlying slices are referenced
// directly and not copied. If the underlying bytes change so will
// the packet
tcpPacket :=
gopacket.NewPacket(
rawBytes,
layers.LayerTypeTCP,
gopacket.NoCopy,
)
fmt.Println(ethPacket)
fmt.Println(ipPacket)
fmt.Println(tcpPacket)
}
示例4: Testv4Defrag
func Testv4Defrag(t *testing.T) {
v4defragger := ip4defrag.NewIPv4Defragmenter()
pack1 := gopacket.NewPacket(testPing1Frag1, layers.LinkTypeEthernet, gopacket.Default)
pack2 := gopacket.NewPacket(testPing1Frag2, layers.LinkTypeEthernet, gopacket.Default)
pack3 := gopacket.NewPacket(testPing1Frag3, layers.LinkTypeEthernet, gopacket.Default)
pack4 := gopacket.NewPacket(testPing1Frag4, layers.LinkTypeEthernet, gopacket.Default)
result, err := v4defragger.DefragIPv4(pack1.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
if err != nil {
t.Fatalf("error defragmenting pack1")
}
if result != nil {
t.Fatalf("unexpected defragmented packet after pack1")
}
result, err = v4defragger.DefragIPv4(pack2.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
if err != nil {
t.Fatalf("error defragmenting pack2")
}
if result != nil {
t.Fatalf("unexpected defragmented packet after pack2")
}
result, err = v4defragger.DefragIPv4(pack3.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
if err != nil {
t.Fatalf("error defragmenting pack3")
}
if result != nil {
t.Fatalf("unexpected defragmented packet after pack3")
}
result, err = v4defragger.DefragIPv4(pack4.Layer(layers.LayerTypeIPv4).(*layers.IPv4))
if err != nil {
t.Fatalf("error defragmenting pack4")
}
if result == nil {
t.Fatalf("missing defragmented packet after pack4")
}
ip := result
// TEST if the ip matches expectation
if ip == nil {
t.Errorf("defrag does not return IPV4 LAYER")
}
if len(ip.LayerPayload()) != 4508 {
t.Fatalf("defrag: expecting a packet of 4508 bytes, got %d", len(ip.LayerPayload()))
}
validPayload := append(testPing1Frag1[34:], testPing1Frag2[34:]...)
validPayload = append(validPayload, testPing1Frag3[34:]...)
validPayload = append(validPayload, testPing1Frag4[34:]...)
if bytes.Compare(validPayload, ip.LayerPayload()) != 0 {
fmt.Println(bytediff.BashOutput.String(
bytediff.Diff(validPayload, ip.LayerPayload())))
t.Errorf("defrag: payload is not correctly defragmented")
}
}
示例5: Layers
// Layers returns gopacket layer representation of this frame. layers contents are all pointer to struct,
// so you can modify the frame information simply setting values to the slice contents directly.
func (self *Frame) Layers() []gopacket.Layer {
if len(self.serialized) != 0 {
self.layers = gopacket.NewPacket(self.serialized, layers.LinkTypeEthernet, gopacket.Lazy).Layers()
self.serialized = self.serialized[:0]
}
return self.layers
}
示例6: getack
func getack(conn net.PacketConn, srcport layers.TCPPort, dstip string) (ack uint32, err error) {
for {
b := make([]byte, 4096)
log.Println("reading from conn")
var n int
var addr net.Addr
n, addr, err = conn.ReadFrom(b)
if err != nil {
log.Println("reading..", err)
return
} else if addr.String() == dstip {
// Decode a packet
packet := gopacket.NewPacket(b[:n], layers.LayerTypeTCP, gopacket.Default)
// Get the TCP layer from this packet
if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
tcp, _ := tcpLayer.(*layers.TCP)
if tcp.DstPort == srcport {
if tcp.SYN && tcp.ACK {
ack = tcp.Seq
} else {
err = errors.New("Port is CLOSED")
}
return
}
}
} else {
err = errors.New("Got packet not matching addr")
}
}
return
}
示例7: v4Defrag
func v4Defrag(v4frag chan gopacket.Packet, normalPack chan gopacket.Packet) error {
defragger := ip4defrag.NewIPv4Defragmenter()
for {
fragpack := <-v4frag
layer := fragpack.Layer(layers.LayerTypeIPv4).(*layers.IPv4)
in, err := defragger.DefragIPv4(layer)
if err != nil {
return err //error handle
} else if in == nil { //part of fragment continue
continue
} else {
b := gopacket.NewSerializeBuffer()
ops := gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}
// it should be remebered that you should copy the payload in when you use SerializeTo
ip_payload, _ := b.PrependBytes(len(in.Payload))
copy(ip_payload, in.Payload)
in.SerializeTo(b, ops)
resultPack := gopacket.NewPacket(b.Bytes(), layers.LayerTypeIPv4, gopacket.Default)
err := resultPack.ErrorLayer()
if err != nil {
fmt.Println("Error decoding some part of the packet:", err) //need error handle here
//return
continue
}
resultPack.Metadata().CaptureLength = len(resultPack.Data())
resultPack.Metadata().Length = len(resultPack.Data())
fmt.Println("defrag a package")
normalPack <- resultPack
}
}
return nil
}
示例8: main
func main() {
var err error
var ci gopacket.CaptureInfo
var frame []byte
sniffer, err := bsdbpf.NewBPFSniffer("alc0", nil)
if err != nil {
panic(err)
}
for {
frame, ci, err = sniffer.ReadPacketData()
if err != nil {
panic(err)
}
fmt.Printf("timeStamp %s\n", ci.Timestamp)
packet := gopacket.NewPacket(frame, layers.LayerTypeEthernet, gopacket.Default)
// Get the TCP layer from this packet
if tcpLayer := packet.Layer(layers.LayerTypeTCP); tcpLayer != nil {
fmt.Println("This is a TCP packet!")
// Get actual TCP data from this layer
tcp, _ := tcpLayer.(*layers.TCP)
fmt.Printf("From src port %d to dst port %d\n", tcp.SrcPort, tcp.DstPort)
}
// Iterate over all layers, printing out each layer type
for _, layer := range packet.Layers() {
fmt.Println("PACKET LAYER:", layer.LayerType())
}
}
}
示例9: TestPacketDot11DataIP
func TestPacketDot11DataIP(t *testing.T) {
p := gopacket.NewPacket(testPacketDot11DataIP, LinkTypeIEEE80211Radio, gopacket.Default)
if p.ErrorLayer() != nil {
t.Error("Failed to decode packet:", p.ErrorLayer().Error())
}
checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11, LayerTypeDot11Data, LayerTypeLLC, LayerTypeSNAP, LayerTypeIPv4, LayerTypeUDP, gopacket.LayerTypePayload}, t)
}
示例10: TestDHCPv4EncodeResponse
func TestDHCPv4EncodeResponse(t *testing.T) {
dhcp := &DHCPv4{Operation: DHCPOpReply, HardwareType: LinkTypeEthernet, Xid: 0x12345678,
ClientIP: net.IP{0, 0, 0, 0}, YourClientIP: net.IP{192, 168, 0, 123}, NextServerIP: net.IP{192, 168, 0, 1}, RelayAgentIP: net.IP{0, 0, 0, 0},
ClientHWAddr: net.HardwareAddr{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc},
ServerName: make([]byte, 64), File: make([]byte, 128)}
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptMessageType, []byte{byte(DHCPMsgTypeOffer)}))
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptSubnetMask, []byte{255, 255, 255, 0}))
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT1, []byte{0x00, 0x00, 0x0e, 0x10}))
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptT2, []byte{0x00, 0x00, 0x0e, 0x10}))
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptLeaseTime, []byte{0x00, 0x00, 0x0e, 0x10}))
dhcp.Options = append(dhcp.Options, NewDHCPOption(DHCPOptServerID, []byte{192, 168, 0, 1}))
buf := gopacket.NewSerializeBuffer()
opts := gopacket.SerializeOptions{FixLengths: true}
err := gopacket.SerializeLayers(buf, opts, dhcp)
if err != nil {
t.Fatal(err)
}
p2 := gopacket.NewPacket(buf.Bytes(), LayerTypeDHCPv4, testDecodeOptions)
dhcp2 := p2.Layer(LayerTypeDHCPv4).(*DHCPv4)
testDHCPEqual(t, dhcp, dhcp2)
fmt.Print(p2)
}
示例11: TestVRRPPacketPacket0
func TestVRRPPacketPacket0(t *testing.T) {
p := gopacket.NewPacket(vrrpPacketPriority100, LinkTypeEthernet, gopacket.Default)
if p.ErrorLayer() != nil {
t.Error("Failed to decode packet", p.ErrorLayer().Error())
}
checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeVRRP}, t)
// Version=2 Type=VRRPv2 Advertisement VirtualRtrID=1 Priority=100
vrrp := p.Layer(LayerTypeVRRP).(*VRRPv2)
if vrrp.Version != 2 {
t.Fatalf("Unable to decode VRRPv2 version. Received %d, expected %d", vrrp.Version, 2)
}
if vrrp.Type != 1 {
t.Fatalf("Unable to decode VRRPv2 type. Received %d, expected %d", vrrp.Type, 1)
}
if vrrp.Priority != 100 {
t.Fatalf("Unable to decode VRRPv2 priority. Received %d, expected %d", vrrp.Priority, 100)
}
if vrrp.Checksum != 47698 {
t.Fatalf("Unable to decode VRRPv2 checksum. Received %d, expected %d", vrrp.Checksum, 47698)
}
}
示例12: Rcv
func (h *arpPktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {
pin := msg.Data().(nom.PacketIn)
p := gopacket.NewPacket([]byte(pin.Packet), layers.LayerTypeEthernet, gopacket.Default)
etherlayer := p.Layer(layers.LayerTypeEthernet)
if etherlayer == nil {
return nil
}
e, _ := etherlayer.(*layers.Ethernet)
if e.EthernetType != layers.EthernetTypeARP {
return nil
}
host, _, err := decodeARP([]byte(pin.Packet))
host.Node = pin.Node
if err != nil {
glog.Errorf("ARP decoding error: %v", err)
return err
}
glog.V(2).Infof("Host detected: %v", host)
ctx.Emit(nom.HostConnected(host))
return nil
}
示例13: TestPacketVXLAN
func TestPacketVXLAN(t *testing.T) {
p := gopacket.NewPacket(testPacketVXLAN, LinkTypeEthernet, gopacket.Default)
if p.ErrorLayer() != nil {
t.Error("Failed to decode packet:", p.ErrorLayer().Error())
}
checkLayers(p, []gopacket.LayerType{LayerTypeEthernet, LayerTypeIPv4, LayerTypeUDP, LayerTypeVXLAN, LayerTypeEthernet, LayerTypeIPv4, LayerTypeICMPv4, gopacket.LayerTypePayload}, t)
if got, ok := p.Layer(LayerTypeVXLAN).(*VXLAN); ok {
want := &VXLAN{
BaseLayer: BaseLayer{
Contents: []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00},
Payload: []byte{0x00, 0x30, 0x88, 0x01, 0x00, 0x02, 0x00, 0x16, 0x3e, 0x37, 0xf6, 0x04, 0x08, 0x00,
0x45, 0x00, 0x00, 0x54, 0x00, 0x00, 0x40, 0x00, 0x40, 0x01, 0x23, 0x4f, 0xc0, 0xa8, 0xcb, 0x03,
0xc0, 0xa8, 0xcb, 0x05, 0x08, 0x00, 0xf6, 0xf2, 0x05, 0x0c, 0x00, 0x01, 0xfc, 0xe2, 0x97, 0x51,
0x00, 0x00, 0x00, 0x00, 0xa6, 0xf8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13,
0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33,
0x34, 0x35, 0x36, 0x37},
},
ValidIDFlag: true,
VNI: 255,
GBPExtension: false,
GBPApplied: false,
GBPDontLearn: false,
GBPGroupPolicyID: 0,
}
if !reflect.DeepEqual(want, got) {
t.Errorf("VXLAN layer mismatch, \nwant %#v\ngot %#v\n", want, got)
}
}
}
示例14: runReader
func (vnet *VNET) runReader(ctx context.Context) {
defer vnet.wg.Done()
var maxPktSize = vnet.iface.MaxPacketSize()
for {
var pkt = NewPacket(maxPktSize)
n, flags, err := vnet.iface.ReadPacket(pkt.buf)
if err == io.EOF {
pkt.Release()
return
}
if err != nil {
pkt.Release()
log.Printf("error during read: %s", err)
time.Sleep(10 * time.Millisecond)
continue
}
pkt.Packet = gopacket.NewPacket(pkt.buf[:n], layers.LayerTypeEthernet, gopacket.NoCopy)
pkt.Flags = flags
pkt.layers = pkt.Layers()
vnet.dispatch(ctx, pkt)
}
}
示例15: TestPacketUSB0
func TestPacketUSB0(t *testing.T) {
p := gopacket.NewPacket(testPacketUSB0, LinkTypeLinuxUSB, gopacket.Default)
if p.ErrorLayer() != nil {
t.Error("Failed to decode packet:", p.ErrorLayer().Error())
}
checkLayers(p, []gopacket.LayerType{LayerTypeUSB, LayerTypeUSBInterrupt}, t)
if got, ok := p.Layer(LayerTypeUSB).(*USB); ok {
want := &USB{
BaseLayer: BaseLayer{
Contents: []uint8{0x0, 0x38, 0x4a, 0x3b, 0x0, 0x88, 0xff, 0xff, 0x43, 0x1, 0x81, 0x1, 0x2, 0x0, 0x2d, 0x0, 0xc0, 0xd3, 0x5b, 0x50, 0x0, 0x0, 0x0, 0x0, 0x8a, 0x85, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0},
Payload: []uint8{0x4},
},
ID: 0xffff88003b4a3800,
EventType: USBEventTypeComplete,
TransferType: USBTransportTypeInterrupt,
Direction: 0x1,
EndpointNumber: 0x1,
DeviceAddress: 0x1,
BusID: 0x2,
TimestampSec: 1348195264,
TimestampUsec: 689546,
Setup: false,
Data: true,
Status: 0,
UrbLength: 0x1,
UrbDataLength: 0x1,
}
if !reflect.DeepEqual(got, want) {
t.Errorf("USB packet processing failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", got, want)
}
}
}