How do I close an open port from the terminal on t

2019-01-29 15:05发布

I opened port #5955 from a java class to comunicate from a client. How do i close this port after I am done? and also which command can show me if port open or closed?

标签: macos port
11条回答
SAY GOODBYE
2楼-- · 2019-01-29 15:05
  1. First find out the Procees id (pid) which has occupied the required port.(e.g 5434)

    ps aux | grep 5434

2.kill that process

   kill -9 <pid>
查看更多
等我变得足够好
3楼-- · 2019-01-29 15:08

To find the process try:

sudo lsof -i :portNumber

Kill the process which is currently using the port using its PID

kill PID

and then check to see if the port closed. If not, try:

kill -9 PID

I would only do the following if the previous didnt work

sudo kill -9 PID

Just to be safe. Again depending on how you opened the port, this may not matter.

查看更多
叛逆
4楼-- · 2019-01-29 15:09

You can also use this first command to kill a process that owns a particular port:

sudo netstat -ap | grep :<port_number>

For example, say this process holds port 8000 TCP, then running the command:

sudo netstat -ap | grep :8000

will output the line corresponding to the process holding port 8000, for example:

tcp  0  0 *:8000   *:* LISTEN  4683/procHoldingPort

In this case, procHoldingPort is the name of the process that opened the port, 4683 is its pid, and 8000 (note that it is TCP) is the port number it holds (which you wish to close).

Then kill the process, following the above example:

kill  4683

As others mentioned here out, if that doesn't work (you can try using kill with -9 as an argument):

kill -9 4683

Again, in general, it's better to avoid sending SIGKILL (-9) if you can.

Cheers,

Guy.

查看更多
劫难
5楼-- · 2019-01-29 15:10
  1. Find out the process ID (PID) which is occupying the port number (e.g., 5955) you would like to free

    sudo lsof -i :5955
    
  2. Kill the process which is currently using the port using its PID

    sudo kill -9 PID
    
查看更多
家丑人穷心不美
6楼-- · 2019-01-29 15:10

When the program that opened the port exits, the port will be closed automatically. If you kill the Java process running this server, that should do it.

查看更多
狗以群分
7楼-- · 2019-01-29 15:10

try below, assuming running port is 8000:

free-port() { kill "$(lsof -t -i :8000)"; }

I found the reference here

查看更多
登录 后发表回答