package main

import ( "fmt" "log" "time"

"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
"github.com/google/gopacket/layers"

)

func main() {

// Set filter for capturing DHCP packets
filter := 'udp and port 67 and port 68'

// Open network interface for capturing packets
iface := 'eth0'
handle, err := pcap.OpenLive(iface, 65535, true, pcap.BlockForever)
if err != nil {
	log.Fatal(err)
}
defer handle.Close()

// Set filter for capturing DHCP packets
if err := handle.SetBPFFilter(filter); err != nil {
	log.Fatal(err)
}

// Capture and process DHCP packets
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
fmt.Println('Capturing DHCP packets on interface', iface)
for packet := range packetSource.Packets() {
	// Extract DHCP layer
	dhcpLayer := packet.Layer(layers.LayerTypeDHCPv4)
	if dhcpLayer != nil {
		dhcpPacket := dhcpLayer.(*layers.DHCPv4)

		// Check if packet direction is inbound
		if packet.Metadata().CaptureInfo.Direction == pcap.DirectionIn {
			fmt.Println('Received DHCP Request from', dhcpPacket.ClientHWAddr, 'with IP', dhcpPacket.ClientIP.String())
		}
	}

	// Wait for 1 second before capturing next packet
	time.Sleep(1 * time.Second)
}

}

// Note: This program requires root privileges to access network interface.

Golang DHCP Packet Sniffer with gopacket: Capture Inbound Requests

原文地址: https://www.cveoy.top/t/topic/lu1X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录