Finding a process using a specific network port with the lsof command

Finding a process using a specific network port with the lsof command

Today I could not launch a node server: the port my app was targeted was already in use. Fortunately Unix comes with very handy command line tools when it comes to finding which processes are using a specific port/address.

No matter what I did, refused to start with the error:

Shell

1

2

3

4

5

Error:listen EADDRINUSE

aterrnoException(net.js:901:11)

atServer._listen2(net.js:1039:14)

atlisten(net.js:1061:10)

atServer.listen(net.js:1127:5)

The only way to fix the problem was to either use another port for my app (I didn’t want to do that) or find the process which used this port and kill it. I’m quite familiar with Unix command line but didn’t know how to do that. After the research, I found the lsof command:

Shell

1

lsof-lists on its standard output fileinformation about files opened by processes

At first it didn’t seem to be useful, but looking at the command line arguments, there is one that’s interesting:

1

2

3

-i

Thisoption selects the listing of files any of whose Internet address matches the address specified ini.

Since at any time there are a lot of connections going on, this returns quite a lot of entries. But we may easily filter them, by using grep. Since the process is waiting for connections, it is likely in LISTEN mode, so we can type:

Shell

1

2

3

4

5

$lsof-i4TCP|grepLISTEN

node98902leo3uIPv40x066158740t0TCP*:http-alt(LISTEN)

node98902leo17uIPv40x055048740t0TCP localhost:6666(LISTEN)

node98902leo18uIPv40x051a9db00t0TCP localhost:6667(LISTEN)

node98903leo3uIPv40x066158740t0TCP*:http-alt(LISTEN)

That’s better: we have two different node processes listening. The good thing about the -i option is that we may add the port as well:

Shell

1

2

3

4

$lsof-i4TCP:8080|grepLISTEN

COMMANDPID USER FD TYPEDEVICE SIZE/OFF NODE NAME

node98902leo3uIPv40x066158740t0TCP*:http-alt(LISTEN)

node98903leo17uIPv40x066158740t0TCP*:http-alt(LISTEN)

We got it! These two processes are using port 8080, for some reason, pm2 didn’t correctly kill them. But we can easily do so ourselves with:

Shell

1

$sudo kill-998902

Note that killing the first one will automatically kill the second process.