网络子系统——notifier测试程序

湛光华
2023-12-01

最近在看<<深入理解Linux网络技术内幕>>,其中讲到了notifier,也就是通知链的使用。特别是在第八章,讲到了在注册链时,register_netdevice_notifier会重放当前系统已注册设备所有过去的NETDEV_REGISTER和NETDEV_UP。处于好奇,写了个测试程序,来看看是否的确这样。

有关通知链的概念和使用请参看<<深入理解Linux网络技术内幕>的第四章和第八章。

测试程序如下:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/notifier.h>  /*For NETDEV_XXX*/
#include <linux/netdevice.h>

static int notifier_test_event(struct notifier_block *self, unsigned long val, void *arg)
{
	struct net_device *dev = arg;

	switch(val){
		case NETDEV_UP:
			printk("device name = %s , event is UP\n", dev->name);
			break;
		case NETDEV_DOWN:
			printk("device name = %s , event is down\n", dev->name);
			break;
		case NETDEV_REGISTER:
			printk("device name = %s , event is REGISTER\n", dev->name);
			break;
		default:
			break;
	}

	return 0;
}

static struct notifier_block notifier_test = {
	.notifier_call = notifier_test_event,
};

static int __init notifier_test_init(void)
{
	return (register_netdevice_notifier(&notifier_test));
}

static void __exit notifier_test_exit(void)
{
	unregister_netdevice_notifier(&notifier_test);
	
}


module_init(notifier_test_init);
module_exit(notifier_test_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("yj4231@hotmail.com");
MODULE_DESCRIPTION("Notifier test");

将该程序编译为模块。然后进行加载,输出如下:

[root@sbc9260 /mnt/nfs/home/bgm]# insmod notifier_test.ko
device name = lo , event is REGISTER
device name = lo , event is UP
device name = eth0 , event is REGISTER
device name = eth0 , event is UP
[root@sbc9260 /mnt/nfs/home/bgm]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:02:34:56:78:19  
          inet addr:192.168.0.134  Bcast:192.168.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:12880 errors:0 dropped:0 overruns:0 frame:0
          TX packets:77 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:892161 (871.2 KiB)  TX bytes:10914 (10.6 KiB)
          Interrupt:21 Base address:0x4000

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

从模块的打印信息和ifconfig的输出来看,eth0和lo的确注册了,并且已经启动了。

随后,对lo设备进行关闭和开启操作,看下输出。

[root@sbc9260 /mnt/nfs/home/bgm]# ifconfig lo down
device name = lo , event is down
[root@sbc9260 /mnt/nfs/home/bgm]# ifconfig lo up
device name = lo , event is UP

 类似资料: