Skip to content

Instantly share code, notes, and snippets.

@Ziul
Last active August 31, 2023 21:52
Show Gist options
  • Save Ziul/d8853739ee0dc936204f32c41d1d640a to your computer and use it in GitHub Desktop.
Save Ziul/d8853739ee0dc936204f32c41d1d640a to your computer and use it in GitHub Desktop.
This code demonstrates network packet capturing and metrics exporting using the Go programming language
package main
import (
"fmt"
"log"
"os"
"os/signal"
"syscall"
"net/http"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
packetsCaptured = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "packets_captured_total",
Help: "Total number of captured packets",
},
[]string{"source", "destination"},
)
)
func init() {
prometheus.MustRegister(packetsCaptured)
}
func main() {
// Create a packet capture handle
ifaceName := "enp5s0" // Replace with your network interface
handle, err := pcap.OpenLive(ifaceName, 1600, true, pcap.BlockForever)
if err != nil {
log.Fatalf("Failed to open capture handle: %v", err)
}
defer handle.Close()
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
// Start capturing packets
go func() {
for packet := range packetSource.Packets() {
// Process packet here
processPacket(packet)
}
}()
// Prometheus metrics
http.Handle("/metrics", promhttp.Handler())
go func() {
log.Fatal(http.ListenAndServe(":8081", nil))
}()
fmt.Println("Packet capture running... Press Ctrl+C to exit.")
// Capture Ctrl+C signal to gracefully exit
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
}
func processPacket(packet gopacket.Packet) {
// Extract source and destination addresses
ipLayer := packet.Layer(layers.LayerTypeIPv4)
if ipLayer != nil {
ip, _ := ipLayer.(*layers.IPv4)
sourceIP := ip.SrcIP.String()
destinationIP := ip.DstIP.String()
// Increment packets captured metric
packetsCaptured.WithLabelValues(sourceIP, destinationIP).Inc()
}
}
@Ziul
Copy link
Author

Ziul commented Aug 31, 2023

It utilizes the github.com/google/gopacket library to capture packets from a specified network interface. The captured packets' source and destination IP addresses are processed, and metrics are incremented using Prometheus. The packets_captured_total metric counts the total number of captured packets between different source and destination IP address pairs. These metrics are then exposed via an HTTP server on port 8081 for Prometheus to scrape. The program can be terminated gracefully by pressing Ctrl+C.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment