Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have been consulted about any way to release a port owned by a third party application that is listening to it. Say the application uses sockets and is listening for an specific port the root now want to claim back without closing the application. I've been unable to give an answer.

Is there any way to close the handle to the port from the terminal or with an specific API (say the root can write and run C++) that can accomplish this?

share|improve this question
up vote 5 down vote accepted

There's no clean way to close an open file (network port or otherwise) in an application that doesn't expect it.

There is a way to close the file under its nose, but the application might not react well. There's a good chance it will crash, which would defeat the purpose. You can execute a system call in a remote process with the ptrace system call. Use lsof or netstat to find the file descriptor you're interested in. Then attach your favorite debugger to the process in question and make it execute a close (or shutdown) system call.

# Usage: shutdown-in-process PID FD
gdb -n -pid "$1" -batch -x /dev/stdin <<EOF
call close($2)

As this has a good chance of crashing the application, because its interface with its environment will no longer match its internal data structure, consider other approaches. In particular, if the purpose is to have a different application listening on a UDP or TCP port, you could redirect traffic to a different port at the level of the network layer (iptables under Linux, pfctl under BSD, …).

share|improve this answer
+5 if I could. This is a well-written answer that gives both a direct answer, potential pitfalls with the direct answer, and an alternative. – Kevin M Jan 8 '11 at 18:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.