demo/linux/pcap/main_inject.c
2024-07-03 15:36:17 +08:00

51 lines
1.5 KiB
C

#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static const uint8_t test_frame[42] = {
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, // dst mac b0:7b:25:00:89:53
0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, // src mac
0x08, 0x06, 0x00, 0x01, 0x08, 0x00, 0x06, 0x04, 0x00, 0x02, // arp reply
0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, // src mac
10, 11, 12, 13, // src ip 192.168.123.100
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, // dst mac b0:7b:25:00:89:53
14, 15, 16, 17 // dst ip 192.168.123.178
};
int main() {
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle;
// 打开网络设备
handle = pcap_open_live("eno1", BUFSIZ, 0, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device: %s\n", errbuf);
return 1;
}
// 构建数据包
u_char packet[1024];
int packet_len = 0;
memcpy(packet, test_frame, 42);
packet_len = 42;
// 发送数据包
int ret = pcap_inject(handle, packet, packet_len);
if (ret == -1) {
fprintf(stderr, "Couldn't send packet: %s\n", pcap_geterr(handle));
pcap_close(handle);
return 1;
} else {
printf("Packet sent successfully (%d bytes)\n", ret);
}
// 关闭网络设备
pcap_close(handle);
return 0;
}