Home Backend Development Golang golang arp request

golang arp request

May 16, 2023 pm 05:51 PM

This article will introduce how to use Golang to send an ARP request to obtain the MAC address of the target device.

ARP (Address Resolution Protocol) is a protocol that resolves network layer addresses (IP addresses) and data link layer addresses (MAC addresses). In a LAN, each device has a unique MAC address that identifies the device. When we know the IP address of the target device, but not its MAC address, we can send an ARP request to obtain the MAC address of the device.

In Golang, we can use the net.InterfaceAddrs() function in the net package to obtain the IP and MAC address of the current device. Then, use the net.ParseIP() function in the net package to parse the target IP address into a variable of type IP. Next, use the gopacket library to build an ARP request packet and send it to the network.

Let us take a look at the sample code:

package main

import (
    "fmt"
    "net"
    "time"

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

func main() {
    // 获取当前设备的IP和MAC地址
    interfaces, err := net.Interfaces()
    if err != nil {
        panic(err)
    }
    var localIP net.IP
    var localMAC net.HardwareAddr
    for _, iface := range interfaces {
        if iface.Flags&net.FlagUp != 0 && iface.Flags&net.FlagLoopback == 0 {
            addrs, err := iface.Addrs()
            if err != nil {
                panic(err)
            }
            for _, addr := range addrs {
                switch addr := addr.(type) {
                case *net.IPNet:
                    if addr.IP.To4() != nil {
                        localIP = addr.IP
                    }
                case *net.IPAddr:
                    if addr.IP.To4() != nil {
                        localIP = addr.IP
                    }
                }
            }
            localMAC = iface.HardwareAddr
            break
        }
    }
    if localIP == nil || localMAC == nil {
        panic("Could not find local IP and MAC addresses")
    }
    fmt.Println("Local IP:", localIP)
    fmt.Println("Local MAC:", localMAC)

    // 目标IP地址
    targetIP := net.ParseIP("192.168.1.1")
    if targetIP == nil {
        panic("Invalid target IP address")
    }
    fmt.Println("Target IP:", targetIP)

    // 使用gopacket构建ARP请求包
    var buf gopacket.SerializeBuffer
    opts := gopacket.SerializeOptions{}
    eth := layers.Ethernet{
        SrcMAC:       localMAC,
        DstMAC:       net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
        EthernetType: layers.EthernetTypeARP,
    }
    arp := layers.ARP{
        AddrType:          layers.LinkTypeEthernet,
        Protocol:          layers.EthernetTypeIPv4,
        HwAddressSize:     6,
        ProtAddressSize:   4,
        Operation:         layers.ARPRequest,
        SourceHwAddress:   []byte(localMAC),
        SourceProtAddress: []byte(localIP.To4()),
        DstHwAddress:      []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
        DstProtAddress:    []byte(targetIP.To4()),
    }
    if err := gopacket.SerializeLayers(&buf, opts, &eth, &arp); err != nil {
        panic(err)
    }

    // 打开网络接口并发送ARP请求包
    handle, err := pcap.OpenLive("eth0", 65535, true, pcap.BlockForever)
    if err != nil {
        panic(err)
    }
    defer handle.Close()
    if err := handle.WritePacketData(buf.Bytes()); err != nil {
        panic(err)
    }

    // 等待一段时间以获得目标设备的MAC地址
    time.Sleep(time.Second)
    packetSource := packetio.NewPacketSource(handle, handle.LinkType())
    for packet := range packetSource.Packets() {
        arpLayer := packet.Layer(layers.LayerTypeARP)
        if arpLayer != nil {
            arpPacket, _ := arpLayer.(*layers.ARP)
            if arpPacket.Operation == layers.ARPReply && bytes.Equal(arpPacket.SourceProtAddress, targetIP.To4()) {
                fmt.Println("Target MAC:", net.HardwareAddr(arpPacket.SourceHwAddress))
                return
            }
        }
    }
    panic("Could not resolve target MAC address")
}
Copy after login

In the sample code, we first use the net package to obtain the IP and MAC address of the current device. Then, use the net.ParseIP() function to parse the target IP address into a variable of type IP. Next, we use the gopacket.SerializeLayers() function to build the ARP request packet. We first define the Ethernet layer, set the source MAC address to the local MAC address, and the destination MAC address to the broadcast address. Then define the ARP layer, set the request type to ARP request, the source MAC address and source IP address to the local MAC address and local IP address, the target MAC address to 0, and the target IP address to the target IP address. Finally, we open the network interface through the pcap.OpenLive() function and write the ARP request packet.

We wait for a while to get the response from the target device. Use the packetio.NewPacketSource() function to get the source of the received data, and then use a for loop to iterate over the received packets. If an ARP response is received and the source IP address is the destination IP address, it means we have obtained the MAC address of the destination device. The program outputs the MAC address of the target device and ends the run.

Using the above code you can easily send an ARP request and get the MAC address of the target device.

The above is the detailed content of golang arp request. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

See all articles