• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env bcc-lua
2--[[
3Copyright 2016 Marek Vavrusa <mvavrusa@cloudflare.com>
4
5Licensed under the Apache License, Version 2.0 (the "License");
6you may not use this file except in compliance with the License.
7You may obtain a copy of the License at
8
9http://www.apache.org/licenses/LICENSE-2.0
10
11Unless required by applicable law or agreed to in writing, software
12distributed under the License is distributed on an "AS IS" BASIS,
13WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14See the License for the specific language governing permissions and
15limitations under the License.
16]]
17-- This program looks at IP, UDP and ICMP packets and
18-- increments counter for each packet of given type seen
19-- Rewrite of https://github.com/torvalds/linux/blob/master/samples/bpf/sock_example.c
20local ffi = require("ffi")
21local bpf = require("bpf")
22local S = require("syscall")
23
24-- Shared part of the program
25local map = bpf.map('hash', 256)
26map[1], map[6], map[17] = 0, 0, 0
27-- Kernel-space part of the program
28bpf.socket('lo', function (skb)
29   local proto = pkt.ip.proto  -- Get byte (ip.proto) from frame at [23]
30   xadd(map[proto], 1)         -- Atomic `map[proto] += 1`
31end)
32-- User-space part of the program
33for _ = 1, 10 do
34   local icmp, udp, tcp = map[1], map[17], map[6]
35   print(string.format('TCP %d UDP %d ICMP %d packets',
36   	     tonumber(tcp or 0), tonumber(udp or 0), tonumber(icmp or 0)))
37   S.sleep(1)
38end