Baby Bro, Part 1: Functions Etc.

[Note: Blogger seems to have done something nasty to my new blog template, so it's back to the old one at least temporarily]

Here's my first "Baby Bro" post. Before getting into using Bro scripting for its intended use of network traffic analysis, I wanted to figure out how to accomplish basic tasks common to most programming languages:

  • Functions
  • Common types and variable definitions
  • Loops
  • Conditionals
  • Iteration of container types
  • Basic string and arithmetic operations
This is the kind of stuff that many programmers can figure out instantly by looking at a language reference sheet, but I think it helps the rest of us to have explicit examples.

I'm not sure if I'll get through all of them in this series, but here's a start: a main dish of functions, with a side of string formatting and concatenation.


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  1 # "add one" is the function name
2 # (i:int) is the variable and type passed into the function
3 # the final "int" is the type returned by the return statement
4 function add_one(received_value:int): int
5 {
6 local returned_value = received_value + 1;
7 return returned_value;
8 }
9
10 # this function shows two strings passed in, returning a string
11 function concat(a:string,b:string): string
12 {
13 return a + " " + b; # one way of doing string concatenation
14 }
15
16 event bro_init() # bro_init() fires when Bro starts running
17 {
18 local x = 3; # defining a local variable
19 local y = add_one(x); # using the first function defined above
20 print fmt("%d + 1 = %d",x,y); # formatted printing as in printf
21
22 print concat("first","second"); # using the second function defined above
23 }

I think this is fairly self explanatory, given the comments. We have two functions:

  • add_one: adds one to whatever integer is passed into the function, and returns the resulting integer.
  • concat: concatenates two strings, separated by a space, and returns the result. There is a built-in string function for this, but I wanted to show that you can also do it with "+".
I also show local variable definition (Bro also has globals, defined with the global keyword) and string formatting. String formatting is basically the same as printf in other languages.

We can run this from the CLI with no PCAP ingestion just to get the standard output:

jswan@so12a:~/bro$ bro test.bro
3 + 1 = 4
first second



Published: January 16 2013

  • category:
  • tags: