现在的位置: 首页 > 综合 > 正文

socket中BPF的设置

2019年01月12日 ⁄ 综合 ⁄ 共 1195字 ⁄ 字号 评论关闭

 *  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));

抱歉!评论已关闭.