특정 ICMP reply 패킷을 필터링하여 수신하기 위한 BPF설정 예제
#include <linux/filter.h> /* BPF : SO_ATTACH_FILTER */
struct sock_filter s_bpf_code[] = { /* ident 가 다르거나 ICMP_ECHOREPLY 가 아닌 경우 버림 */
BPF_STMT(BPF_LDX | BPF_B | BPF_MSH, 0), /* Skip IP header due BSD, see ping6. */
BPF_STMT(BPF_LD | BPF_H | BPF_IND, 4), /* Load icmp echo ident */
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 1, 0), /* Ours? */
BPF_STMT(BPF_RET | BPF_K, 0), /* Echo with wrong ident. Reject. */
BPF_STMT(BPF_LD | BPF_B | BPF_IND, 0), /* Load icmp type */
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP_ECHOREPLY, 0, 1), /* Echo? */
BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */
BPF_STMT(BPF_RET | BPF_K, 0) /* Echo with wrong reply. Reject. */
};
struct sock_fprog s_filter;
s_filter.len = (unsigned short)(sizeof(s_bpf_code) / sizeof(struct sock_filter));
s_filter.filter = (struct sock_filter *)(&s_bpf_code[0]);
s_bpf_code[2] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, (uint32_t)(s_my_icmp_identification & 0xffffu), 1 /* true jump */, 0 /* false jump */);
setsockopt(s_socket, SOL_SOCKET, (int)(SO_ATTACH_FILTER), (const void *)(&s_filter), (socklen_t)sizeof(s_filter));
특정 ICMPv6 reply 패킷을 필터링하여 수신하기 위한 BPF설정 예제
struct sock_filter s_bpf_code[] = { /* ident 가 다르거나 ICMP6_ECHO_REPLY 가 아닌 경우 버림 */
BPF_STMT(BPF_LD | BPF_H | BPF_ABS, 4), /* Load icmp echo ident */
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA, 1, 0), /* Ours? */
BPF_STMT(BPF_RET | BPF_K, 0), /* Echo with wrong ident. Reject. */
BPF_STMT(BPF_LD | BPF_B | BPF_ABS, 0), /* Load icmp type */
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ICMP6_ECHO_REPLY, 0, 1), /* Echo? */
BPF_STMT(BPF_RET | BPF_K, ~0U), /* Yes, it passes. */
BPF_STMT(BPF_RET | BPF_K, 0) /* Echo with wrong reply. Reject. */
};
struct sock_fprog s_filter;
s_filter.len = (unsigned short)(sizeof(s_bpf_code) / sizeof(struct sock_filter));
s_filter.filter = (struct sock_filter *)(&s_bpf_code[0]);
s_bpf_code[1] = (struct sock_filter)BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, (uint32_t)(s_my_icmp_identification & 0xffffu), 1 /* true jump */, 0 /* false jump */);
setsockopt(s_socket, SOL_SOCKET, (int)(SO_ATTACH_FILTER), (const void *)(&s_filter), (socklen_t)sizeof(s_filter));