Address already in use but nothing in netstat or lsof

pgmillon picture pgmillon · May 28, 2014 · Viewed 15.2k times · Source

I try to start the Python SimpleHTTPServer on port 7054 :

$ sudo python -m SimpleHTTPServer 7054
...
socket.error: [Errno 98] Address already in use

So, I ran the following commands :

$ sudo netstat -ntpu | grep 7054
$ sudo lsof -i -n -P | grep 7054

But I have no results.

Answer

michaeljoseph picture michaeljoseph · Jul 18, 2014

From the netstat manpage:

netstat   [address_family_options]   [--tcp|-t]   [--udp|-u]   [--raw|-w]   [--listening|-l]  [--all|-a]  [--numeric|-n]  [--numeric-hosts]  [--numeric-ports]
[--numeric-users] [--symbolic|-N] [--extend|-e[--extend|-e]] [--timers|-o] [--program|-p] [--verbose|-v] [--continuous|-c]

I use the following options:

sudo netstat -tanl | grep 7054

Which is --numeric, --tcp, --all, --listening

I think the minimal netstat options you need to show the pid of the process listening on a particular port are -nlp.

The lsof options you specify work for me. Using the example code at https://wiki.python.org/moin/UdpCommunication#Receiving and python -m SimpleHTTPServer 7054:

$ netstat -nlp | grep 7054
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:7054            0.0.0.0:*               LISTEN      20458/python    
udp        0      0 0.0.0.0:7054          0.0.0.0:*                           20498/python    
$ lsof -i -n -P | grep 7054
python    20458 michael    3u  IPv4 143736      0t0  TCP *:7054 (LISTEN)
python    20498 michael    3u  IPv4 173739      0t0  UDP *:7054 

Extra credit: stick it in an alias:

listening() {
    netstat -nlp | grep $1
}

And use it:

$ listening 7054