下面是一个用 DPDK 随机发送长度为 arr
数组中的值的 100 个数据包的示例代码:
#include <stdlib.h>
#include <time.h>
#include <rte_mbuf.h>
#include <rte_ethdev.h>
#define NUM_PACKETS 100
int main(int argc, char *argv[]) {
int ret;
uint16_t port_id = 0; // 网口 ID,假设为 0
uint16_t queue_id = 0; // 队列 ID,假设为 0
struct rte_mempool *mbuf_pool;
// 初始化 EAL
ret = rte_eal_init(argc, argv);
if (ret < 0) {
rte_exit(EXIT_FAILURE, "Error: Failed to initialize EAL.\n");
}
// 创建内存池,用于分配 mbuf 结构体
mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_PACKETS*2,
RTE_CACHE_LINE_SIZE, 0,
RTE_MBUF_DEFAULT_BUF_SIZE,
rte_socket_id());
if (mbuf_pool == NULL) {
rte_exit(EXIT_FAILURE, "Error: Failed to create mbuf pool.\n");
}
// 配置网口
ret = rte_eth_dev_configure(port_id, 1, 1, NULL);
if (ret < 0) {
rte_exit(EXIT_FAILURE, "Error: Failed to configure Ethernet device.\n");
}
// 激活网口
ret = rte_eth_dev_start(port_id);
if (ret < 0) {
rte_exit(EXIT_FAILURE, "Error: Failed to start Ethernet device.\n");
}
// 构造并发送数据包
struct ether_hdr *eth_hdr;
struct rte_mbuf *mbuf;
int packet_len;
srand(time(NULL)); // 使用系统时间作为随机数种子
for (int i = 0; i < NUM_PACKETS; i++) {
// 随机选择一个长度
int index = rand() % 6;
packet_len = arr[index];
// 创建 mbuf 结构体
mbuf = rte_pktmbuf_alloc(mbuf_pool);
if (mbuf == NULL) {
rte_exit(EXIT_FAILURE, "Error: Failed to allocate mbuf.\n");
}
// 设置以太网头部
eth_hdr = rte_pktmbuf_mtod(mbuf, struct ether_hdr *);
memset(eth_hdr->d_addr.addr_bytes, 0xFF, ETHER_ADDR_LEN); // 目的地址为广播地址
memset(eth_hdr->s_addr.addr_bytes, 0x00, ETHER_ADDR_LEN); // 源地址为全零地址
eth_hdr->ether_type = htons(ETHER_TYPE_IPv4); // 假设使用 IPv4 协议
// 复制随机生成的数据到 mbuf 中
char *data = (char *)rte_pktmbuf_append(mbuf, packet_len);
for (int j = 0; j < packet_len; j++) {
data[j] = 'A' + rand() % 26; // 将数据填充成 A~Z 的字符序列中的随机字母
}
mbuf->pkt_len = RTE_BE16(packet_len + sizeof(struct ether_hdr));
mbuf->data_len = RTE_BE16(packet_len);
ret = rte_eth_tx_burst(port_id, queue_id, &mbuf, 1);
if (ret != 1) {
printf("Warning: Failed to send packet %d.\n", i+1);
} else {
printf("Packet %d sent successfully.\n", i+1);
}
}
rte_eth_dev_stop(port_id); // 停止网口
rte_eth_dev_close(port_id); // 关闭网口
return 0;
}
在这个示例代码中,我们使用 rand()
函数生成随机数,并将系统时间作为随机数种子。每次循环中,随机选择一个长度,并使用该长度创建 mbuf 结构体。然后,我们填充数据并设置以太网头部和 pkt_len
和 data_len
字段,并发送数据包。
输出结果类似于:
Packet 1 sent successfully.
Packet 2 sent successfully.
...
Packet 99 sent successfully.
Packet 100 sent successfully.