a function of who is sending or listening

Hi All,
I am developing a personal firewall on windows 2k , XP , as a part of that
program , I need a way to know ,
if there is any program or any process ,trying to use any port on my
computer as a server or a client (sending or recieving packets).
the program has to scan all ports and give me the id of the process or the
name of the program that is using any port.
so i need exactly (a function or a way) that for example take a port
number as a parameter and return the program name or process id.
thank you for reading , waiting for your reply.