乐鑫技术交流
直播中

辛太励

7年用户 1125经验值
擅长:20153
私信 关注
[问答]

如何手动往esp32 arp列表中添加自定义的arp绑定信息?

我目前需要手动往esp32 arp列表中添加自定义的arp绑定信息,而非arp请求获得,因为另一方设备无法完成arp应答
如IP为:192.168.88.2 MAC为:00:0A:35:01:FE:C0
arp绑定后我需要实现往192.168.88.2发送udp数据
                                                                                                                                                                                                                        
               

回帖(1)

郭大

2024-6-7 10:54:49
要在ESP32上手动添加自定义的ARP绑定信息,您可以使用以下步骤:

1. 首先,确保您的ESP32设备已经连接到网络,并具有正确的IP地址。

2. 使用以下代码片段在ESP32上创建一个自定义的ARP绑定:

```c
#include "esp_wifi.h"
#include "esp_system.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_eth.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "lwip/dns.h"
#include "lwip/ip4.h"

#define IP_ADDRESS "192.168.88.2"
#define MAC_ADDRESS "00:0A:35:01:FE:C0"

static void add_custom_arp_entry(void) {
    ip4_addr_t ip_addr;
    mac_addr_t mac_addr;

    // 设置IP地址
    inet_aton(IP_ADDRESS, &ip_addr);
    // 设置MAC地址
    mac_addr.addr[0] = 0x00;
    mac_addr.addr[1] = 0x0A;
    mac_addr.addr[2] = 0x35;
    mac_addr.addr[3] = 0x01;
    mac_addr.addr[4] = 0xFE;
    mac_addr.addr[5] = 0xC0;

    // 添加ARP绑定
    etharp_add_static_entry(&ip_addr, &mac_addr);
}

void app_main() {
    // 初始化WiFi和网络接口
    // ...

    // 添加自定义ARP绑定
    add_custom_arp_entry();

    // 其他代码
    // ...
}
```

3. 在`app_main()`函数中调用`add_custom_arp_entry()`函数,以在ESP32上添加自定义的ARP绑定。

4. 现在,您可以使用ESP32向IP地址为192.168.88.2的设备发送UDP数据。以下是一个发送UDP数据的示例:

```c
#include "lwip/udp.h"

#define DESTINATION_IP "192.168.88.2"
#define DESTINATION_PORT 12345
#define LOCAL_PORT 1234

static void send_udp_packet(void) {
    struct udp_pcb *pcb;
    struct pbuf *p;
    const char *data = "Hello, UDP!";

    pcb = udp_new();
    udp_bind(pcb, IP_ADDR_ANY, LOCAL_PORT);

    p = pbuf_alloc(PBUF_TRANSPORT, strlen(data), PBUF_RAM);
    pbuf_take(p, (const void *)data, strlen(data));

    ip_addr_t dest_ip;
    inet_aton(DESTINATION_IP, &dest_ip);
    udp_sendto(pcb, p, &dest_ip, DESTINATION_PORT);

    pbuf_free(p);
    udp_remove(pcb);
}

void app_main() {
    // 初始化WiFi和网络接口
    // ...

    // 添加自定义ARP绑定
    add_custom_arp_entry();

    // 发送UDP数据
    send_udp_packet();

    // 其他代码
    // ...
}
```

5. 将上述代码添加到您的ESP32项目中,并根据您的需求进行调整。这样,您就可以手动添加自定义的ARP绑定信息,并使用ESP32向指定的IP地址发送UDP数据了。
举报

更多回帖

发帖
×
20
完善资料,
赚取积分