Refer:
Linux Kernel:
dev_get_by_index() prototype ↗
dev_get_by_index() implementation ↗
Here is the copy paste of dev_get_by_index() API implementation (net/core/dev.c) from the Kernel-source version 6.6 for quick reference:
/* Deprecated for new users, call netdev_get_by_index() instead */
struct net_device *dev_get_by_index(struct net *net, int ifindex)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_index_rcu(net, ifindex);
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_index);
Download this episode my entire kernel module sample code, make file, clean script HERE.
Here is my sample source-code discussed in the video:
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/skbuff.h>
#include <linux/udp.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_arp.h>
#include <linux/icmp.h>
#include <linux/netlink.h>
#include <linux/mroute.h>
#include <net/checksum.h>
#include <net/inet_ecn.h>
#include <net/xfrm.h>
#include <net/route.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/tcp.h>
#include <net/arp.h>
#include <net/udp.h>
#include <net/icmp.h>
#include <net/inetpeer.h>
#include <net/protocol.h>
#include <net/flow.h>
#include <asm/types.h>
static int mymodule_init(void)
{
struct net_device *dev=dev_get_by_index(&init_net, 1);
if(dev!=NULL)
{ printk("Dev: name: %s - ifindex: %d\n", dev->name, dev->ifindex); }
return 0;
}
static void mymodule_exit(void)
{
}
module_init(mymodule_init);
module_exit(mymodule_exit);
Its makefile:
obj-m += Kernel_module.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules