Wednesday, June 8, 2011

How to close an open port in unix/linux environments

In many cases it is not uncommon to see exception like "java.net.BindException: Address already in use" when running programs. Sometimes this exception occurs even after the program that was using the particular address/port has been terminated. That is mostly due to improperly terminated application. Here the port is still assigned to the process of the particular program. How can we release the port and let the new program use that specific port, without throwing address already in use exceptions.

First let's find the process attached to the program running on the particular port.
pradeeban@pradeeban:~/LB/wso2lb-1.0.0/bin$ lsof | grep 8243
notificat  1802  pradeeban  txt       REG                8,4     53296   13638243 /usr/lib/gnome-panel/notification-area-applet
firefox-b  1821  pradeeban   52u     IPv4             896036       0t0        TCP pradeeban.local:43306->pradeeban.local:8243 (ESTABLISHED)
java      10500  pradeeban  113u     IPv6             867578       0t0        TCP pradeeban.local:8243->pradeeban.local:45898 (CLOSE_WAIT)
java      10500  pradeeban  300u     IPv6             867966       0t0        TCP pradeeban.local:8243->pradeeban.local:46006 (CLOSE_WAIT)
java      10500  pradeeban  471u     IPv6             858667       0t0        TCP *:8243 (LISTEN)
Here, lsof lists open files. From the above command, we notice that a process having the pid of 10500 is listening on the port 8243.

If you know the name of the running application process or part of it, you can use
ps -xa | grep
instead, to get the pid.

Now we can easily release the port 8243 by killing the relevant process (process of pid 10500).
pradeeban@pradeeban:~/LB/wso2lb-1.0.0/bin$ kill 10500

No comments:

Post a Comment

You are welcome to provide your opinions in the comments. Spam comments and comments with random links will be deleted.