Created
August 10, 2024 02:56
-
-
Save sullemanhossam/a0f87716267373e864dadcaf51e00a3f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mac | |
import ( | |
"fmt" | |
"network-chesswork/utilities" | |
"time" | |
"github.com/google/gopacket" | |
"github.com/google/gopacket/layers" | |
"github.com/google/gopacket/pcap" | |
) | |
func Sniff(iface string) error { | |
if iface == "" { | |
return fmt.Errorf("network interface is required") | |
} else { | |
fmt.Println("Sniffing package received interface", iface) | |
} | |
// Open the network interface for packet capture | |
handle, err := pcap.OpenLive(iface, 1600, true, pcap.BlockForever) | |
if err != nil { | |
return fmt.Errorf("failed to open live capture: %w", err) | |
} | |
defer handle.Close() | |
packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) | |
macAddresses := make(map[string]bool) | |
for packet := range packetSource.Packets() { | |
// Extract Ethernet layer | |
ethernetLayer := packet.Layer(layers.LayerTypeEthernet) | |
if ethernetLayer == nil { | |
continue | |
} | |
ethernetPacket, ok := ethernetLayer.(*layers.Ethernet) | |
if !ok { | |
continue | |
} | |
srcMAC := ethernetPacket.SrcMAC.String() | |
dstMAC := ethernetPacket.DstMAC.String() | |
if !macAddresses[srcMAC] { | |
macAddresses[srcMAC] = true | |
fmt.Println("Source MAC Address:", srcMAC) | |
path := "./temp/source-mac.json" | |
data := map[string]interface{}{ | |
srcMAC: map[string]interface{}{ | |
"time": time.Now().UTC().Format(time.RFC3339), | |
}, | |
} | |
if err := utilities.AppendJSON(path, data); err != nil { | |
return fmt.Errorf("failed to append source MAC address to JSON: %w", err) | |
} | |
} | |
if !macAddresses[dstMAC] { | |
macAddresses[dstMAC] = true | |
fmt.Println("Destination MAC Address:", dstMAC) | |
path := "./temp/dest-mac.json" | |
data := map[string]interface{}{ | |
dstMAC: map[string]interface{}{ | |
"time": time.Now().UTC().Format(time.RFC3339), | |
}, | |
} | |
if err := utilities.AppendJSON(path, data); err != nil { | |
return fmt.Errorf("failed to append destination MAC address to JSON: %w", err) | |
} | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment