In addition to the advice above, you need to buy
TCP/IP Illustrated, Volume 1: The Protocols.
Essentially you're asking how to write a firewall and intrusion detection program. you have a wide range of protocols that you'll need to understand, as it's not as simple as just watching for connections. On a modern OS, there are lots of connections going in and out of your PC. Making sense of them is a huge task.
The netstat advice above, is a good start in getting a handle on what you're PC is already doing.