socket中BPF的设置

本文介绍了一种使用BPF(Berkeley Packet Filter)进行DHCP数据包过滤的方法,通过检查数据包类型、协议、端口号等条件,筛选并处理符合特定条件的数据包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 *  This packet filter checks for the following conditions.
 *    - Ethernet Type = IP (0x0800)
 *    - IP Protocol Type = UDP (17)
 *    - Not an IP fragment
 *    - UDP Port = DHCP Client (68)
 *
 *  If all of the above conditions are met, this frame is copied (via a
 *  call to recv) to the DhcpCMgr for processing. Otherwise, the frame

 *  is dropped by the Linux stack.


定义BPF:

static struct sock_filter dhcp_bpf_filter [] = {
    /* Make sure this is an IP packet... */
    BPF_STMT (BPF_LD + BPF_H + BPF_ABS, 12),
    BPF_JUMP (BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 0, 8),


    /* Make sure it's a UDP packet... */
    BPF_STMT (BPF_LD + BPF_B + BPF_ABS, 23),
    BPF_JUMP (BPF_JMP + BPF_JEQ + BPF_K, IPPROTO_UDP, 0, 6),


    /* Make sure this isn't a fragment... */
    BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 20),
    BPF_JUMP(BPF_JMP + BPF_JSET + BPF_K, 0x1fff, 4, 0),


    /* Get the IP header length... */
    BPF_STMT (BPF_LDX + BPF_B + BPF_MSH, 14),


    /* Make sure it's to the right port... */
    BPF_STMT (BPF_LD + BPF_H + BPF_IND, 16),
    BPF_JUMP (BPF_JMP + BPF_JEQ + BPF_K, 68, 0, 1),


    /* If we passed all the tests, ask for the whole packet. */
    BPF_STMT(BPF_RET+BPF_K, (u_int)-1),


    /* Otherwise, drop it. */
    BPF_STMT(BPF_RET+BPF_K, 0),
};


设置BPF:

    struct sock_fprog pf;

    memset(&pf, 0, sizeof(pf));
    pf.filter = dhcp_bpf_filter;
    pf.len    = dhcp_bpf_filter_len;
    rc = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &pf, sizeof(pf));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值