• Alexei Starovoitov's avatar
    samples: bpf: example of stateful socket filtering · 03f4723e
    Alexei Starovoitov authored
    this socket filter example does:
    - creates arraymap in kernel with key 4 bytes and value 8 bytes
    
    - loads eBPF program which assumes that packet is IPv4 and loads one byte of
      IP->proto from the packet and uses it as a key in a map
    
      r0 = skb->data[ETH_HLEN + offsetof(struct iphdr, protocol)];
      *(u32*)(fp - 4) = r0;
      value = bpf_map_lookup_elem(map_fd, fp - 4);
      if (value)
           (*(u64*)value) += 1;
    
    - attaches this program to raw socket
    
    - every second user space reads map[IPPROTO_TCP], map[IPPROTO_UDP], map[IPPROTO_ICMP]
      to see how many packets of given protocol were seen on loopback interface
    
    Usage:
    $sudo samples/bpf/sock_example
    TCP 0 UDP 0 ICMP 0 packets
    TCP 187600 UDP 0 ICMP 4 packets
    TCP 376504 UDP 0 ICMP 8 packets
    TCP 563116 UDP 0 ICMP 12 packets
    TCP 753144 UDP 0 ICMP 16 packets
    Signed-off-by: default avatarAlexei Starovoitov <ast@plumgrid.com>
    Signed-off-by: default avatarDavid S. Miller <davem@davemloft.net>
    03f4723e
libbpf.c 2.67 KB