二。回环网卡的程序设计
/*************************** *******回环网卡的驱动程序*** ***********吕晓宁*********** *********2015.12.26********* ***************************/ #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的值写入到寄存器中 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->rx_packets = packets; stats->tx_packets = packets; return stats; } struct net_device_ops loopback_ops = { .ndo_start_xmit = loopback_xmit, .ndo_get_stats = loopback_get_stats, }; void static loopback_setup(struct net_device *dev) { //2. net_dev初始化参数 dev->mtu = (16*1024)+20+20+12; dev->flags = IFF_LOOPBACK; dev->header_ops = ð_header_ops; dev->netdev_ops = &loopback_ops; } /* Setup and register the loopback device. */ static __net_init int loopback_net_init(struct net *net) { int err = -ENOMEM; //1. 分配net_device结构 dev = alloc_netdev(0,"lo%d",loopback_setup); //4.完成net_device的注册 err = 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, };