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.
Asked
Active
Viewed 1,461 times
1

Drew
- 12,578
- 11
- 58
- 98
-
1I'm guessing a more helpful question would have been "Why does the program say the port is in use after restarting it, even though lsof shows nothing?" which is [answered here](https://stackoverflow.com/a/3233022/1899640) – that other guy Feb 03 '22 at 20:39
1 Answers
0
You can check the process using netstat
. It will give the pid of the process.
To check the port 8080 , you can do
nabil@LAPTOP~$ netstat -natup | grep 8080
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 63610/test-py
Here an example
nabil@LAPTOP:~$ netstat -natupe
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program name
tcp 0 0 127.0.0.1:5010 0.0.0.0:* LISTEN 1000 261855 66050/confd.smp
tcp 0 0 127.0.0.53:53 0.0.0.0:*
tcp6 0 0 127.0.0.1:50736 127.0.0.1:4569 ESTABLISHED 1000 697733 63666/java
tcp6 0 0 127.0.0.1:41145 127.0.0.1:49159 TIME_WAIT 0 0 -
tcp6 0 0 127.0.0.1:41145 127.0.0.1:44619 TIME_WAIT 0 0 -
udp 0 0 127.0.0.53:53 0.0.0.0:* 101 23138 -

Nabil
- 1,130
- 5
- 11