I have a program that occasionally fails to start because an IP/port that it wants to connect to is already in use. How can I programatically check which process is using the port? I can manually run lsof after I notice the failure, but whatever process is using the port must be using it for a very short time because by the time I run lsof, it says nothing is using the port. Thus, I'd like to programmatically find which process is using the port, immediately after the failure to connect, within the program that failed. How can I do this? It must be possible, because lsof does it.