看看網路驅動文件系統的構造操作
先構造一個虛擬的網卡
根據上面的分析,參考 drivers\net\cs89x0.c 寫自己的虛擬網卡設備驅動
1分配分配一個net_device結構體
2 設置
2.1 寫一個發包函數virt_net_send_packet
這時候寫出這個函數
1 netif_stop_queue() //發數據時,先停止網卡的隊列
2 emulator_rx_packet()
構造一個假包,因爲我們ping其他網段的時候,不存在這個網段,那我們就把數據再傳回到本機
在裏面僞造數據
static void emulator_rx_packet(struct sk_buff *skb, struct net_device *dev)
{
/* 參考LDD3 */
unsigned char *type;
struct iphdr *ih;
__be32 *saddr, *daddr, tmp;
unsigned char tmp_dev_addr[ETH_ALEN];
struct ethhdr *ethhdr;
struct sk_buff *rx_skb;
// 從硬件讀出/保存數據
/* 對調"源/目的"的mac地址 */
ethhdr = (struct ethhdr *)skb->data;
memcpy(tmp_dev_addr, ethhdr->h_dest, ETH_ALEN);
memcpy(ethhdr->h_dest, ethhdr->h_source, ETH_ALEN);
memcpy(ethhdr->h_source, tmp_dev_addr, ETH_ALEN);
/* 對調"源/目的"的ip地址 */
ih = (struct iphdr *)(skb->data + sizeof(struct ethhdr));
saddr = &ih->saddr;
daddr = &ih->daddr;
tmp = *saddr;
*saddr = *daddr;
*daddr = tmp;
//((u8 *)saddr)[2] ^= 1; /* change the third octet (class C) */
//((u8 *)daddr)[2] ^= 1;
type = skb->data + sizeof(struct ethhdr) + sizeof(struct iphdr);
//printk("tx package type = %02x\n", *type);
// 修改類型, 原來0x8表示ping
*type = 0; /* 0表示reply */
ih->check = 0; /* and rebuild the checksum (ip needs it) */
ih->check = ip_fast_csum((unsigned char *)ih,ih->ihl);
// 構造一個sk_buff
rx_skb = dev_alloc_skb(skb->len + 2);
skb_reserve(rx_skb, 2); /* align IP on 16B boundary */
memcpy(skb_put(rx_skb, skb->len), skb->data, skb->len);
/* Write metadata, and then pass to the receive level */
rx_skb->dev = dev;
rx_skb->protocol = eth_type_trans(rx_skb, dev);
rx_skb->ip_summed = CHECKSUM_UNNECESSARY; /* don't check it */
dev->stats.rx_packets++;
dev->stats.rx_bytes += skb->len;
// 提交sk_buff
netif_rx(rx_skb);
}
發送的包++ 發送的字節數(skbuff裏面的長度)
2.3 設置mac地址
3 註冊
代碼測試
裝載驅動
配置該網卡的 ip
現在 ping 3.3.3.4 可以傳回數據