Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

1 Answer 1

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.

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

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
1  
+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

 
discard

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.