Skip to content

Instantly share code, notes, and snippets.

@herry13
Created February 17, 2017 02:32
Show Gist options
  • Save herry13/9720014388230989f4244916b9b9f677 to your computer and use it in GitHub Desktop.
Save herry13/9720014388230989f4244916b9b9f677 to your computer and use it in GitHub Desktop.
Catching ARP packet in Go
package main
import (
"fmt"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"log"
"net"
)
func printDevices() {
// find all devices
devices, err := pcap.FindAllDevs()
if err != nil {
log.Fatal(err)
}
// print device information
for _, device := range devices {
fmt.Println("Interface: ", device.Name)
for _, address := range device.Addresses {
var ipType string
if ipType = "IPv4"; len(address.IP) == 4 {
ipType = "IPv6"
}
fmt.Println("- IP address: ", address.IP, " ", ipType)
fmt.Println("- Subnet mask: ", address.Netmask)
}
}
}
func listenToDevice(device string) error {
fmt.Println("Listening on device ", device)
// Open a pcap handler to read packets
handle, err := pcap.OpenLive(device, 65536, true,
pcap.BlockForever)
if err != nil {
return err
}
// Create a new PacketDataSource
src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
// Packets returns a channel of packets
in := src.Packets()
for {
var packet gopacket.Packet
select {
//case <-stop:
// break
case packet = <-in:
arpLayer := packet.Layer(layers.LayerTypeARP)
if arpLayer == nil {
continue
}
arp := arpLayer.(*layers.ARP)
log.Println("Source hardware address ",
net.HardwareAddr(arp.SourceHwAddress).String(),
"\nDestination hardware address ",
net.HardwareAddr(arp.DstHwAddress).String(),
"\nOperation ",
arp.Operation)
}
}
defer handle.Close()
return nil
}
func main() {
if err := listenToDevice("wlan0"); err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment