2.6.30核心Netfilter的簡單例子、四(filterIp)

來源:互聯網
上載者:User

將革命進行到底,再來一個netfilter例子,這次是過濾指定IP地址的資料包。

1、原始碼:filterIp.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netdevice.h>

MODULE_LICENSE("GPL");

/* This is the structure we shall use to register our function */
static struct nf_hook_ops nfho;

/* IP address we want to drop packets from, in NB order */
static unsigned char *drop_ip = "/x7f/x00/x00/x01";   /* 127.0.0.1 */

/* This is the hook function itself */
unsigned int hook_func(unsigned int hooknum,
                           struct sk_buff *skb,
                           const struct net_device *in,
                           const struct net_device *out,
                           int (*okfn)(struct sk_buff *))
{
  struct sk_buff *sb = skb;
  struct iphdr *iph;

  iph = ip_hdr(sb);

  if (iph->saddr == *(unsigned int *)drop_ip)
  {
    printk("Dropped packet from... %d.%d.%d.%d/n",
                *drop_ip, *(drop_ip + 1), *(drop_ip + 2),*(drop_ip + 3));
    return NF_DROP;
  }
  else
  {
    return NF_ACCEPT;
  }

}
/* Initialisation routine */
int init_module()
{
  /* Fill in our hook structure */
  nfho.hook     = hook_func;         /* Handler function */
  nfho.hooknum  = NF_INET_PRE_ROUTING; /* First hook for IPv4 */
  nfho.pf       = PF_INET;
  nfho.priority = NF_IP_PRI_FIRST;   /* Make our function first */

  nf_register_hook(&nfho);

  pr_info("filterIp install into kernel!/n");
  return 0;
}
/* Cleanup routine */
void cleanup_module()
{
  nf_unregister_hook(&nfho);
  pr_info("filterIp removed from kernel!/n");
}

2、Makefile:

obj-m +=filterIp.o
all:
  make -C /lib/modules/`uname -r`/build M=`pwd`
clean:
  make -C /lib/modules/`uname -r`/build M=`pwd` clean
install:
  /sbin/insmod filterIp.ko
remove:
  /sbin/rmmod filterIp

3、編譯:

make

4、安裝模組:

make install

5、測試:

ping 127.0.0.1

查看/var/log/messages,有如下字樣:

 

Sep 11 11:15:40 vm04 kernel: Dropped packet from... 127.0.0.1

6、卸載模組:

make remove

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.