How to properly close a port?

Sylwia Vargas - Mar 30 '20 - - Dev Community

This is a thing I need to google every now and then so here's a simple recipe for closing neglected ports on MacOS, Windows and Linux.


Mac OS

Here are the steps:

1. Find the process ID (PID) of the port (replace the 'portNumber' with the number)

sudo lsof -i :portNumber

This will give you a response as follows — copy the PID number for the next step:

2. Kill the process

First, try this (replace PID with the number you copied above):

kill PID

Now, test if it's closed by connecting to the port (replace portNumber with the actual port number):

nc localhost portNumber

If it returns immediately with no output, the port isn't open. However, if it returns some input, try to kill it with:

kill -9 PID

Again, try to connect. If it's still running, try this:

sudo kill -9 PID


Windows

Here are the steps for Windows:

1. Find the process ID (PID) of the port (replace the 'portNumber' with the number)

netstat -ano | findstr :portNumber

Copy the PID number for the next step.

2. Kill the process

First, try this (replace typeyourPIDhere with the number you copied above):

taskkill /PID typeyourPIDhere /F

Run the first command again to see if it's closed.


Linux

Here are the steps for Linux (courtesy of mayankjoshi)

1. Get a list of all open processes

$top

2. Kill a process

kill pid kills the process by process id
killall pname kills the process by name
-9 for forceful killing in both kill and killall
Use sudo if it's a root process.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player