go 语言的抓包库使用例子

package main

import (
    "fmt"
    "github.com/google/gopacket"
    "github.com/google/gopacket/pcap"
    "log"
    "time"
)
var (
    device string = "en0"
    snapshot_len int32 = 1024
    promiscuous bool = false
    err error
    timeout time.Duration = 30 * time.Second
    handle * pcap.Handle
)

func main (){
       // 监听在线 网卡, en0是我的笔记本网卡名称。
    handle,err = pcap.OpenLive(device,snapshot_len,promiscuous,timeout)
    if err != nil {
        log.Fatal(err)
    }
    defer handle.Close()

    packetSource := gopacket.NewPacketSource(handle,handle.LinkType())
        
       // 循环抓包,并打印
    for packet := range packetSource.Packets(){
        fmt.Println(packet)
    }
}

结果:

PACKET: 54 bytes, wire length 54 cap length 54 @ 2018-09-11 17:29:57.560295 +0800 CST
- Layer 1 (14 bytes) = Ethernet {Contents=[..14..] Payload=[..40..] SrcMAC=00:88:65:3e:xx:xx DstMAC=ec:26:ca:6d:xx:xx EthernetType=IPv4 Length=0}
- Layer 2 (20 bytes) = IPv4 {Contents=[..20..] Payload=[..20..] Version=4 IHL=5 TOS=0 Length=40 Id=29992 Flags= FragOffset=0 TTL=64 Protocol=TCP Checksum=29434 SrcIP=192.168.20.106 DstIP=192.30.253.124 Options=[] Padding=[]}
- Layer 3 (20 bytes) = TCP  {Contents=[..20..] Payload=[] SrcPort=64109 DstPort=443(https) Seq=588680355 Ack=1656732130 DataOffset=5 FIN=false SYN=false RST=false PSH=false ACK=true URG=false ECE=false CWR=false NS=false Window=4096 Checksum=17570 Urgent=0 Options=[] Padding=[]}
    原文作者:asmcos
    原文地址: https://www.jianshu.com/p/273475ef5c02
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞