2010-12-20 104 views
12

我一直在尋找net/core/dev.c和其他文件來試圖找出如何獲取當前配置的網絡設備列表,它證明是有點難找。獲取Linux內核中的網絡設備列表

最終目標是能夠使用dev.c中的dev_get_stats獲取網絡設備統計信息,但我需要知道當前接口,以便我可以抓取net_device結構體來傳入。我必須在內部執行此操作內核,因爲我正在編寫一個模塊,它添加了一個新的/ proc /入口,這涉及到來自當前網絡設備的一些統計信息,所以從我可以收集的內容中必須在內核中完成。

如果有人可以指示我如何獲得接口,將不勝感激。

+0

你能解決我的這個查詢: http://stackoverflow.com/questions/36917950/unable-從網絡設備內核模塊中獲取MAC地址 – 2016-04-28 18:29:43

回答

14

這應該做的伎倆:

#include <linux/netdevice.h> 

struct net_device *dev; 

read_lock(&dev_base_lock); 

dev = first_net_device(&init_net); 
while (dev) { 
    printk(KERN_INFO "found [%s]\n", dev->name); 
    dev = next_net_device(dev); 
} 

read_unlock(&dev_base_lock); 
+4

需要鎖定('dev_base_lock')對列表的併發更新。 – caf 2010-12-21 00:15:21

+0

非常好!像魅力一樣工作,看起來像我在看錯文件歡呼! – 2010-12-21 00:47:27

+0

你也可以解決我的查詢,如果可能的話, http://stackoverflow.com/questions/36917950/unable-to-fetch-mac-address-from-net-device-in-kernel-module – 2016-04-28 18:28:59

14

給定一個struct net *net識別淨命名空間,你有興趣,你應該抓住dev_base_lock和使用for_each_netdev()

read_lock(&dev_base_lock); 
for_each_netdev(net, dev) { 
    /* Inspect dev */ 
} 
read_unlock(&dev_base_lock); 

(在較新內核,您可以使用RCU,但在這種情況下可能是過度複雜)。


要獲得net命名空間的使用,你應該register_pernet_subsys()來註冊你proc文件:

static const struct file_operations foostats_seq_fops = { 
    .owner = THIS_MODULE, 
    .open = foostats_seq_open, 
    .read = seq_read, 
    .llseek = seq_lseek, 
    .release = foostats_seq_release, 
}; 

static int foo_proc_init_net(struct net *net) 
{ 
    if (!proc_net_fops_create(net, "foostats", S_IRUGO, 
      &foostats_seq_fops)) 
     return -ENOMEM; 
    return 0; 
} 

static void foo_proc_exit_net(struct net *net) 
{ 
    proc_net_remove(net, "foostats"); 
} 


static struct pernet_operations foo_proc_ops = { 
    .init = foo_proc_init_net, 
    .exit = foo_proc_exit_net, 
}; 

register_pernet_subsys(&foo_proc_ops) 

在你foostats_seq_open()功能,你拿上net命名空間的引用,並把它在發佈功能:

static int foostats_seq_open(struct inode *inode, struct file *file) 
{ 
    int err; 
    struct net *net; 

    err = -ENXIO; 
    net = get_proc_net(inode); 
    if (net == NULL) 
     goto err_net; 

    err = single_open(file, foostats_seq_show, net); 
    if (err < 0) 
     goto err_open; 

    return 0; 

err_open: 
    put_net(net); 
err_net: 
    return err; 
} 

static int foostats_seq_release(struct inode *inode, struct file *file) 
{ 
    struct net *net = ((struct seq_file *)file->private_data)->private; 

    put_net(net); 
    return single_release(inode, file); 
} 

foostats_seq_show()函數可以ñ獲得net,行走裝置,收集統計信息,併產生輸出:如果你有答案

static int sockstat6_seq_show(struct seq_file *seq, void *v) 
{ 
    struct net *net = seq->private; 
    struct net_device *dev; 

    int foostat, barstat; 

    read_lock(&dev_base_lock); 
    for_each_netdev(net, dev) { 
     /* Inspect dev */ 
    } 
    read_unlock(&dev_base_lock); 

    seq_printf(seq, "Foo: %d\n", foostat); 
    seq_printf(seq, "Bar: %d\n", barstat); 

    return 0; 
} 
相關問題