socket中BPF的设置

来源:互联网 发布:网络和信息化建设规划 编辑:程序博客网 时间:2024/06/16 13:04
 *  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));

0 0
原创粉丝点击