TCP port assignment

I have multiple processes running the same program on my linux machine. For each process I want to be able to use a unique (available) TCP port. I have thought of using netstat to check which ports are available for use however, the time-window between checking and selecting might expose some race condition as other process might already snatch it... How can I accomplish this and avoid this situation in shell scripting?

A UNIX system probably won't let you open more than one TCP socket on the same port anyhow, the bind() call will fail. But you could just let the server decide what port to use, it'll auto-assign a port in the 32768-65535 range when you bind with port 0.