C -UDP数据包使用Linux -Kernel模块发送,而无需使用套接字



我正在编写一个创建IP数据包的内核模块。现在,我想发送此数据包,但没有为其传输创建任何插座。

有什么方法可以在内核例程的帮助下直接发送。

由于我已经跟踪了数据包传输的Linux内核代码,因此在> net/core/core/dev.c 中定义了一个函数。我们可以使用吗?

实际上我不想使用插座。

您不需要套接字即可在内核中发送UDP数据包,您只需要分配一个SKB,然后独自构造IP标头和UDP标头,最后将其发送出去由dev_queue_xmit()。

skb = alloc_skb(len, GFP_ATOMIC);
if (!skb)
        return;
skb_put(skb, len);
skb_push(skb, sizeof(*udph));
skb_reset_transport_header(skb);
udph = udp_hdr(skb);
udph->source = htons(....);
udph->dest = htons(...);
udph->len = htons(udp_len);
udph->check = 0;
udph->check = csum_tcpudp_magic(local_ip,
                                remote_ip,
                                udp_len, IPPROTO_UDP,
                                csum_partial(udph, udp_len, 0));
if (udph->check == 0)
        udph->check = CSUM_MANGLED_0;
skb_push(skb, sizeof(*iph));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
/* iph->version = 4; iph->ihl = 5; */
put_unaligned(0x45, (unsigned char *)iph);
iph->tos      = 0;
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, &(iph->saddr));
put_unaligned(remote_ip, &(iph->daddr));
iph->check    = ip_fast_csum((unsigned char *)iph, iph->ihl);
eth = (struct ethhdr *) skb_push(skb, ETH_HLEN);
skb_reset_mac_header(skb);
skb->protocol = eth->h_proto = htons(ETH_P_IP);
memcpy(eth->h_source, dev->dev_addr, ETH_ALEN);
memcpy(eth->h_dest, remote_mac, ETH_ALEN);
skb->dev = dev;

dev_queue_xmit(skb);

最新更新