我试图在 linux 内核模块中制作一个自定义 skb,然后通过网络发送它。我成功地制作了一个 SKB,但是当我通过网络发送它时,它没有到达目的地。
如果我在通过网络发送我的 SBK 的本地机器上运行 wireshark,它会显示我的数据包。但是,如果我检查数据包的内容,则表明数据被放置为“以太网拖车”
此外,如果我从我的 SKB 中删除所有数据并仅发送一个仅包含标头的 SKB,它仍然无法到达其目的地
这是代码:
u_int32_t local_ip;
u_int32_t remote_ip;
struct udphdr *udph;
struct iphdr *iph;
struct ethhdr *eth;
unsigned short udp_len;
char remote_mac[6];
char local_mac[6];
分配一个skb:
int header_len = sizeof(*iph) + sizeof(*udph) + sizeof(*eth);
skb = sock_wmalloc(sock->sk, /*payload len*/ len + header_len + LL_RESERVED_SPACE(pfr->ring_netdev->dev), 0, GFP_KERNEL);
由于我使用的是 skb_push,因此我将数据向下移动并一直向下移动:
skb_reserve(skb,
len + header_len + LL_RESERVED_SPACE(pfr->ring_netdev->dev));
推送 UDP 标头:
skb_push(skb, sizeof(*udph));
相应地重置 transport_pointer:
skb_reset_transport_header(skb);
设置并填充 udp 标头:
udph = udp_hdr(skb);
udph->source = htons(5123);
udph->dest = htons(5123);
udp_len = 14;
udph->len = htons(udp_len);
udph->check = 0;
local_ip = htonl(0xCB873F2A); /*203.135.63.42*/
remote_ip = htonl(0xCB873F29); /*203.135.61.41*/
udph->check = csum_tcpudp_magic(local_ip,
remote_ip,
udp_len, IPPROTO_UDP,
csum_partial(udph, udp_len, 0));
if (udph->check == 0) {
printk("mangled checksum\n");
udph->check = CSUM_MANGLED_0;
}
现在推送 IP 标头:
skb_push(skb, sizeof(*iph));
重置network_pointer:
skb_reset_network_header(skb);
设置并填充网络标头:
iph = ip_hdr(skb);
put_unaligned(0x45, (unsigned char *)iph);
iph->tos = 0;
ip_len = 40;
put_unaligned(htons(ip_len), &(iph->tot_len));
//iph->id = htons(atomic_inc_return(&ip_ident));
iph->frag_off = 0;
iph->ttl = 64;
iph->protocol = IPPROTO_UDP;
iph->check = 0;
put_unaligned(local_ip /*"\xC0\xA8\x00\x01"*/, &(iph->saddr));
put_unaligned(remote_ip /*"\xC0\xA8\x00\x01"*/, &(iph->daddr));
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
推送以太网报头:
eth = (struct ethhdr *) skb_push(skb, ETH_HLEN);
相应地重置 mac_pointer:
skb_reset_mac_header(skb);
设置并填充 mac_header:
skb->protocol = eth->h_proto = htons(ETH_P_IP);
remote_mac[0] = 0x4C;
remote_mac[1] = 0x72;
remote_mac[2] = 0xB9;
remote_mac[3] = 0x24;
remote_mac[4] = 0x14;
remote_mac[5] = 0x1E;
local_mac[0] = 0x00;
local_mac[1] = 0x1E;
local_mac[2] = 0xE3;
local_mac[3] = 0xED;
local_mac[4] = 0xD4;
local_mac[5] = 0xA9;
memcpy(eth->h_source, remote_mac, ETH_ALEN);
memcpy(eth->h_dest, remote_mac, ETH_ALEN);
设置设备和协议:
skb->protocol = htons(ETH_P_IP);
skb->dev = pfr->ring_netdev->dev;
skb->priority = sock->sk->sk_priority;
if(!err)
goto out_free;
现在发送
if (dev_queue_xmit(skb) != NETDEV_TX_OK) {
err = -ENETDOWN; /* Probably we need a better error here */
goto out;
}