回环网卡驱动程序设计

Ifconfig中的lo就是回环网卡,回环网卡的tx和rx连接在一起,不连接任何介质的时候相互也能ping通

编写回环网卡驱动

内核代码中的loopback.c就是内核提供好的回环网卡lo驱动

#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/errno.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/init.h>

#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/io.h>

#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/ethtool.h>
#include <net/sock.h>
#include <net/checksum.h>
#include <linux/if_ether.h>	/* For the statistics structure. */
#include <linux/if_arp.h>	/* For ARPHRD_ETHER */
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/percpu.h>
#include <net/net_namespace.h>

unsigned long bytes = 0;
unsigned long packets = 0;

struct net_device *dev;

int loopback_xmit(struct sk_buff *skb, struct net_device *dev)
{
	skb->protocol = eth_type_trans(skb,dev);

	bytes +=skb->len;
	packets++;

	netif_rx(skb);		//回环网卡中将数据包送回协议栈

	return 0;
}

static struct net_device_stats *loopback_get_stats(struct net_device *dev)
{
	struct net_device_stats *stats = &dev->stats;
	stats->tx_bytes  =bytes;
	stats->rx_bytes  =bytes;
	stats->tx_packets  =packets;
	stats->rx_packets  =packets;

	return stats;

}

struct net_device_ops loopback_ops  =
{
	.ndo_strat_xmit = loopback_xmit,
	.ndo_get_stats = loopback_get_stats,


};


void static loopback_setup(struct net_device *dev)
{

	dev->mtu = (16*1024)+20+20+12;		//mtu表示能够接受的最大包的大小
	dev->flags = IFF_LOOPBACK;
	dev->header_ops = &eth_header_ops;		//构造数据包的头操作的函数

	//2.初始化net_device网卡
	dev->netdev_ops = &loopback_ops;		//网卡所支持的操作



}


static __net_init int loopback_net_init(struct net *net)
{
	//1.分配net_device结构

	dev = alloc_netdev(0,"lo",loopback_setup);			//表明一个成员,网卡名字,函数(用来初始化的)
	//2.初始化net_device网卡

	//3.初始化硬件,由于回环网卡不存在硬件问题所以不做硬件初始化

	//4.注册网卡驱动
	Register_netdev(dev);

	net->loopback_dev = dev;

	return 0;
}

static __net_exit void loopback_net_exit(struct net *net)
{
	unregister_netdev(dev);

}

/* Registered in net/core/dev.c */
struct pernet_operations __net_initdata loopback_net_ops = {
       .init = loopback_net_init,
       .exit = loopback_net_exit,
};

猜你喜欢

转载自blog.csdn.net/weixin_41937674/article/details/82990374