How can I kill a process running on a specific IP and port?

18,030

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
Share:
18,030

Related videos on Youtube

Stephen
Author by

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, 2022

Comments

  • Stephen
    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
      Jeff Schaller almost 7 years
      by "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
      Jeff Schaller almost 7 years
    • Stephen
      Stephen almost 7 years
      I already know about fuser, and by running I mean listening to. It is Ubuntu 14.04, and IP and port are local.
    • Jeff Schaller
      Jeff Schaller almost 7 years
      please edit your question (and tags) to clarify
  • MoonCheese62
    MoonCheese62 almost 7 years
    grep 80 would match something like 172.217.22.280:45581. I don't think that's intentional. You probably want to do a match like ss -tanp | awk '$1=="LISTEN" && $4=="<IP>:<PORT>" { print $6 }'
  • man0v
    man0v almost 7 years
    Yes it will... I need a better regex. Will update it.
  • Tom Hale
    Tom Hale almost 7 years
    Please provide the answer with explanation so that your answer stands alone.
  • cat
    cat almost 7 years
    What's wrong with this answer? Explain your votes, se vous plaît