How can I kill a process running on a specific IP and port?
Solution 1
There are likely cleaner ways, but something along the lines of:
netstat -lnp | grep 'tcp .*127.0.0.1:9984' | sed -e 's/.*LISTEN *//' -e 's#/.*##' | xargs kill
Solution 2
Using ss
we can get details of process/connections which are listening on a specific IP and port, for src 127.0.0.1
and port 80
:
sudo ss -lp '( dport = :80 )' src 127.0.0.1
then we can only get the PID
's using grep
and kill them all using xargs
and kill
.
sudo ss -lp '( dport = :80 )' src 127.0.0.1 | grep -Po "(?<=pid=).*(?=,)"\
| sort | uniq | xargs kill
You can also use -a
switch instead of -l
to get a list of all listening and non-listening sockets.
Solution 3
fuser
on Linux has an option which does exactly what you are looking to do.
For example, fuser 80/tcp
will print the PID of the process bound on that port and fuser -k 80/tcp
will kill that process.
Solution 4
On linux, as root, you can use either
ss -ptan
or
netstat -ntulp
to get a list of all running processes that "listen"(in this case tcp, replace the "t" with "u" for udp).
So one liner, to kill process listening on port 80, would look something like that:
ss -tanp | grep 80 | head -1 | sed 's_.*pid=\(.*\),.*_\1_' | xargs kill
Related videos on Youtube
Stephen
Growing in development with languages such as PHP, JavaScript, Java, and more. Currently working on own projects for developmental and experimental purposes.
Updated on September 18, 2022Comments
-
Stephen over 1 year
I was wondering, is there any way to kill a process that is running on a specific IP and port on Ubuntu 14.04 on a local IP and port? Preferably, this would be in one command, but if not, a bash script would be perfectly fine as well.
-
Jeff Schaller almost 7 yearsby "running" do you mean "listening" or "connected to", and by IP do you mean local or remote, and by port, do you mean local or remote? What Operating System?
-
Jeff Schaller almost 7 years
-
Stephen almost 7 yearsI already know about fuser, and by running I mean listening to. It is Ubuntu 14.04, and IP and port are local.
-
Jeff Schaller almost 7 yearsplease edit your question (and tags) to clarify
-
-
MoonCheese62 almost 7 years
grep 80
would match something like172.217.22.280:45581
. I don't think that's intentional. You probably want to do a match likess -tanp | awk '$1=="LISTEN" && $4=="<IP>:<PORT>" { print $6 }'
-
man0v almost 7 yearsYes it will... I need a better regex. Will update it.
-
Tom Hale almost 7 yearsPlease provide the answer with explanation so that your answer stands alone.
-
cat almost 7 yearsWhat's wrong with this answer? Explain your votes, se vous plaît