I would like to know how does a firewall Monitor all incoming connections blocking some and allowing others to connect to their target service... ??

Sample code (if available is highly apreciated , no matter how trivial it is i just want to get the concept )