以下是DPDK输出数据包的IP地址、MAC地址和TCP端口的示例代码:
#include <rte_mbuf.h>
#include <rte_ether.h>
#include <rte_ip.h>
#include <rte_tcp.h>
static void print_packet_info(struct rte_mbuf *pkt) {
// Ethernet header
struct ether_hdr *eth_hdr = rte_pktmbuf_mtod(pkt, struct ether_hdr *);
printf("Src MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
eth_hdr->s_addr.addr_bytes[0], eth_hdr->s_addr.addr_bytes[1],
eth_hdr->s_addr.addr_bytes[2], eth_hdr->s_addr.addr_bytes[3],
eth_hdr->s_addr.addr_bytes[4], eth_hdr->s_addr.addr_bytes[5]);
printf("Dst MAC: %02X:%02X:%02X:%02X:%02X:%02X\n",
eth_hdr->d_addr.addr_bytes[0], eth_hdr->d_addr.addr_bytes[1],
eth_hdr->d_addr.addr_bytes[2], eth_hdr->d_addr.addr_bytes[3],
eth_hdr->d_addr.addr_bytes[4], eth_hdr->d_addr.addr_bytes[5]);
// IP header
struct ipv4_hdr *ip_hdr = (struct ipv4_hdr *)((uint8_t *)eth_hdr + sizeof(struct ether_hdr));
printf("Src IP: %u.%u.%u.%u\n",
(ip_hdr->src_addr >> 24) & 0xFF, (ip_hdr->src_addr >> 16) & 0xFF,
(ip_hdr->src_addr >> 8) & 0xFF, ip_hdr->src_addr & 0xFF);
printf("Dst IP: %u.%u.%u.%u\n",
(ip_hdr->dst_addr >> 24) & 0xFF, (ip_hdr->dst_addr >> 16) & 0xFF,
(ip_hdr->dst_addr >> 8) & 0xFF, ip_hdr->dst_addr & 0xFF);
// TCP header
struct tcp_hdr *tcp_hdr = (struct tcp_hdr *)((uint8_t *)ip_hdr + sizeof(struct ipv4_hdr));
printf("Src Port: %u\n", rte_be_to_cpu_16(tcp_hdr->src_port));
printf("Dst Port: %u\n", rte_be_to_cpu_16(tcp_hdr->dst_port));
}
该函数可以从rte_mbuf
指针中获取数据包的以太网头部、IP头部和TCP头部,然后打印出源MAC地址、目的MAC地址、源IP地址、目的IP地址、源TCP端口和目的TCP端口。注意,此代码假定数据包是IPv4和TCP。如果使用不同的协议(如IPv6或UDP),则需要相应地更改代码。