Who is listening on a given TCP port on Mac OS X?
Asked Answered
I

19

2116

On Linux, I can use netstat -pntl | grep $PORT or fuser -n tcp $PORT to find out which process (PID) is listening on the specified TCP port. How do I get the same information on Mac OS X?

Investment answered 12/12, 2010 at 12:30 Comment(3)
Sorry, netstat -p tcp | grep $PORT doesn't display PIDs since netstat on the Mac OS X cannot display PIDs.Investment
netstat -anv displays the port on Mac OS X (source: solution below by @SeanHamiliton)Conceal
From the comment above: netstat -anv gave me PID on Mac OS X (10.15.7 Catalina)Hawkweed
I
3250

On macOS Big Sur and later, use this command:

sudo lsof -i -P | grep LISTEN | grep :$PORT

or to just see just IPv4:

sudo lsof -nP -i4TCP:$PORT | grep LISTEN

On older versions, use one of the following forms:

sudo lsof -nP -iTCP:$PORT | grep LISTEN
sudo lsof -nP -i:$PORT | grep LISTEN

Substitute $PORT with the port number or a comma-separated list of port numbers.

sudo may not be needed if you need information on ports above 1023.

The -n flag is for displaying IP addresses instead of host names. This makes the command execute much faster, because DNS lookups to get the host names can be slow (several seconds or a minute for many hosts).

The -P flag is for displaying raw port numbers instead of resolved names like http, ftp or more esoteric service names like dpserve, socalia.

See the comments for more options.

For completeness, because frequently used together:

To kill the PID:

sudo kill -9 <PID>
# kill -9 60401
Investment answered 12/12, 2010 at 12:39 Comment(14)
Prefix this with sudo to see processes you don't own.Diwan
on lion, worked with a change sudo lsof -i TCP:$PORT | grep LISTENShien
On Mountain Lion, you don't need grep: sudo lsof -iTCP:$PORT -sTCP:LISTENNiersteiner
after so many searches this one is the best. people who directly want to copy the command should replace $PORT with actual port number or define the variable PORT and that too for multiple ports like: export PORT=8080,4433; lsof -n -i4TCP:$PORTMarketplace
On my OSX 10.9.2 it even runs without the preceding sudo. Might give that a try, as it enables you to run it without entering a password. :)Ramonitaramos
One does not need sudo if the port to investigate is above 1024.Ruyter
All three work for me on Sierra, but I needed sudo even for a port above 1024 - perhaps it depends on who's running the process.Gantt
@meagar - you rolled back my edit to include the OS version. Was it factually incorrect or what was the reason for the rollback? I think it makes sense to note which commands work on what OS X versions, so people easier find the appropriate command.Bouse
after that you can use kill -9 <the-f-ing-pid> to eliminate itEveretteeverglade
Handy one line command to kill a process on a TCP port read K_PORT; lsof -iTCP:$K_PORT -sTCP:LISTEN | tail -n 1 | awk '{ print $2 }' | xargs kill -9Exaggerative
I have error: lsof: unacceptable port specification in: -i 4TCPBroomfield
Instead of | grep LISTEN I recommend using sed so you can also see the column headers | sed -n '1p;/LISTEN/p'Pornography
Note that -P is important to prevent displaying port numbers as service names. From man lsof: Inhibits the conversion of port numbers to port names for network files. Inhibiting the conversion may make lsof run a little faster. It is also useful when port name lookup is not working properly.Selfconfessed
When killing the PID you may not want to jump straight to -9 — I will generally try kill -HUP <PID> and kill -INT <PID> first. Those give the process a chance to clean up, while kill -KILL <PID> (-KILL == -9) nukes the process from orbit.Inmost
S
977

Every version of macOS supports this:

sudo lsof -iTCP -sTCP:LISTEN -n -P

Personally I've end up with this simple function in my ~/.bash_profile:

listening() {
    if [ $# -eq 0 ]; then
        sudo lsof -iTCP -sTCP:LISTEN -n -P
    elif [ $# -eq 1 ]; then
        sudo lsof -iTCP -sTCP:LISTEN -n -P | grep -i --color $1
    else
        echo "Usage: listening [pattern]"
    fi
}

Then listening command gives you a listing of processes listening on some port and listening smth greps this for some pattern.

Having this, it's quite easy to ask about particular process, e.g. listening dropbox, or port, e.g. listening 22.

lsof command has some specialized options for asking about port, protocol, process etc. but personally I've found above function much more handy, since I don't need to remember all these low-level options. lsof is quite powerful tool, but unfortunately not so comfy to use.

Shushan answered 4/5, 2015 at 12:11 Comment(4)
This is going in my dotfiles. I search every few months and always come upon this answer.Hymnist
I feel this should be accepted answer as OP said he does -pntl, which would list all services. The accepted answer asks for one or more port numbers to be specified, which is not remotely the same.Kenton
This works on Monterey 12.1 as well for me.Spile
For those linux-challenged like me, you might need to edit ~/.zshrc to work with the default terminal with MacOSLuxe
R
474

You can also use:

sudo lsof -i -n -P | grep TCP

This works in Mavericks.

Rugger answered 22/1, 2014 at 22:13 Comment(6)
The -i option makes it significantly faster. 0.02 seconds vs 2 seconds. In my application this made quite the difference.Millionaire
what do those specific flags do -i, -n, -P. I can't find anywhere what they mean exactlyNailhead
sudo lsof -i -n -P | grep TCP | grep $PORT - I made an alias with this commandGarfieldgarfinkel
I would suggest adding "| grep $PORT" or "| grep LISTEN"Toady
Great! Works also on Mojave.Malindamalinde
@ChadWatkins: -i limits to internet "files" -P gives port numbers not nice names -n will give IP addresses rather than hostnames -P and -n both make lsof -i run faster. You can use man lsof to get more infoGeneralissimo
I
407

Update January 2016

Really surprised no-one has suggested:

lsof -i :PORT_NUMBER

to get the basic information required. For instance, checking on port 1337:

lsof -i :1337

Other variations, depending on circumstances:

sudo lsof -i :1337
lsof -i tcp:1337

You can easily build on this to extract the PID itself. For example:

lsof -t -i :1337

which is also equivalent (in result) to this command:

lsof -i :1337 | awk '{ print $2; }' | head -n 2 | grep -v PID

Quick illustration:

enter image description here

For completeness, because frequently used together:

To kill the PID:

kill -9 <PID>
# kill -9 60401

or as a one liner:

kill -9 $(lsof -t -i :1337)
Insomnia answered 7/1, 2016 at 15:45 Comment(4)
This command also displays non-listener PIDs, and the questions explicitly asked for listeners only.Investment
You can also run lsof -t -i :1338. -t will return the process id, so you won't have to awk/head.Cheerless
Nothing worked except kill -9 $(lsof -t -i :5000) on el capitanFabyola
This is great. I prefer to know what's there before I kill it, so (based on this) I just added to my bashrc: whatsonport() { ps -ef | grep `lsof -t -i :$1` }, so: ⇒ whatsonport 3000 --> 501 14866 14865 0 6:07AM ttys006 0:01.73 node .Syllogistic
E
96

For the LISTEN, ESTABLISHED and CLOSED ports:

sudo lsof -n -i -P | grep TCP

For the LISTEN ports only:

sudo lsof -n -i -P | grep LISTEN

For a specific LISTEN port (e.g. port 80):

sudo lsof -n -i -P | grep ':80 (LISTEN)'

Or if you just want a compact summary [no service/apps described], go by netstat. The good side here is, no sudo needed:

netstat -a -n | grep 'LISTEN '

Explaining the options used

lsof options (for more details see man lsof):

  • -n suppress the host name
  • -i for IPv4 and IPv6 protocols
  • -P omit port names

netstat options (for more details see man netstat):

  • -a for all sockets
  • -n don't resolve names, show network addresses as numbers

Tested on High Sierra 10.13.3 and Mojave 10.14.3

The last syntax netstat works on Linux too [apt install net-tools]

lsof comes by default on some Linux distribution

Evette answered 8/12, 2018 at 7:22 Comment(1)
The detail explanations are actually very useful for beginners like me. thanks @PYKDziggetai
H
56

on OS X you can use the -v option for netstat to give the associated pid.

type:

netstat -anv | grep [.]PORT

the output will look like this:

tcp46      0      0  *.8080                 *.*                    LISTEN      131072 131072   3105      0

The PID is the number before the last column, 3105 for this case

Hafiz answered 3/11, 2015 at 8:6 Comment(2)
You also need to add grep LISTEN to show the listeners only.Investment
This is what I needed! lsof couldn't find the port. but netstat showed it was open. -v was the secret sauce I lacked.Malaise
Z
41

On macOS, here's an easy way to get the process ID that's listening on a specific port with netstat. This example looks for a process serving content on port 80:

find server running on port 80

netstat -anv | egrep -w [.]80.*LISTEN

sample output

tcp4  0 0  *.80       *.*    LISTEN      131072 131072    715      0

The 2nd from the last column is the PID. In above, it's 715.

options

-a - show all ports, including those used by servers

-n - show numbers, don't look up names. This makes the command a lot faster

-v - verbose output, to get the process IDs

-w - search words. Otherwise the command will return info for ports 8000 and 8001, not just "80"

LISTEN - give info only for ports in LISTEN mode, i.e. servers

Zipah answered 14/1, 2018 at 22:14 Comment(1)
the -v flag made itBiauriculate
T
22

On the latest macOS version you can use this command:

lsof -nP -i4TCP:$PORT | grep LISTEN

If you find it hard to remember then maybe you should create a bash function and export it with a friendlier name like so

vi ~/.bash_profile

and then add the following lines to that file and save it.

function listening_on() {
    lsof -nP -i4TCP:"$1" | grep LISTEN
}

Now you can type listening_on 80 in your Terminal and see which process is listening on port 80.

Tiny answered 5/6, 2018 at 12:32 Comment(0)
R
15

On Snow Leopard (OS X 10.6.8), running 'man lsof' yields:

lsof -i 4 -a

(actual manual entry is 'lsof -i 4 -a -p 1234')

The previous answers didn't work on Snow Leopard, but I was trying to use 'netstat -nlp' until I saw the use of 'lsof' in the answer by pts.

Rothenberg answered 25/8, 2013 at 19:14 Comment(0)
Q
14

I wanted to share this command which works well and prints the headers so you know which column is which:

lsof -iTCP:8080 -sTCP:LISTEN -P -n

Example Output: enter image description here

Quinte answered 8/5, 2023 at 16:24 Comment(0)
T
11

I am a Linux guy. In Linux it is extremely easy with netstat -ltpn or any combination of those letters. But in Mac OS X netstat -an | grep LISTEN is the most humane. Others are very ugly and very difficult to remember when troubleshooting.

Tartaric answered 17/8, 2016 at 18:57 Comment(1)
The question explicitly asked for a specific TCP port, and your commands show listeners on all ports.Investment
E
9
lsof -n -i | awk '{ print $1,$9; }' | sort -u

This displays who's doing what. Remove -n to see hostnames (a bit slower).

Epistrophe answered 3/5, 2014 at 9:35 Comment(6)
Your answer is not bad, but it's on a question with several highly-upvoted answers, and an accepted one, from multiple years ago. In the future, try to focus on more recent questions, especially ones that have not yet been answered.Marcellemarcellina
Does this command display non-TCP ports as well, and non-listeners as well? The question explicitly asks for listeners on TCP ports only.Investment
As per lsof(8) man page: If no address is specified, this option [-i] selects the listing of all Internet and x.25 (HP-UX) network files.Epistrophe
@Misha Tavkhelidze: So it displays non-listeners as well, so it doesn't answer the question.Investment
Add -sTCP:LISTEN to lsofEpistrophe
that shows not only ports being listened to, but also outbound connections?Speiss
Z
9

checkout this project/tool: procs

install on MacOs: brew install procs

This allows you control what to display with procs.

To see TCP/UDP Ports, add below to ~/.procs.toml after installing the tool.

[[columns]]
kind = "TcpPort"
style = "BrightYellow|Yellow"
numeric_search = true
nonnumeric_search = false
align = "Left"

[[columns]]
kind = "UdpPort"
style = "BrightGreen|Green"
numeric_search = false
nonnumeric_search = true
align = "Left"

Here is a sample output:

enter image description here

Zygosis answered 29/8, 2021 at 20:46 Comment(0)
E
4

This did what I needed.

ps -eaf | grep `lsof -t -i:$PORT`
Ez answered 10/5, 2017 at 8:29 Comment(0)
U
3

I made a small script to see not only who is listening where but also to display established connections and to which countries. Works on OSX Siera

#!/bin/bash
printf "\nchecking established connections\n\n"
for i in $(sudo lsof -i -n -P | grep TCP | grep ESTABLISHED | grep -v IPv6 | 
grep -v 127.0.0.1 | cut -d ">" -f2 | cut -d " " -f1 | cut -d ":" -f1); do
    printf "$i : " & curl freegeoip.net/xml/$i -s -S | grep CountryName | 
cut -d ">" -f2 | cut -d"<" -f1
done

printf "\ndisplaying listening ports\n\n"

sudo lsof -i -n -P | grep TCP | grep LISTEN | cut -d " " -f 1,32-35

#EOF

Sample output
checking established connections

107.178.244.155 : United States
17.188.136.186 : United States
17.252.76.19 : United States
17.252.76.19 : United States
17.188.136.186 : United States
5.45.62.118 : Netherlands
40.101.42.66 : Ireland
151.101.1.69 : United States
173.194.69.188 : United States
104.25.170.11 : United States
5.45.62.49 : Netherlands
198.252.206.25 : United States
151.101.1.69 : United States
34.198.53.220 : United States
198.252.206.25 : United States
151.101.129.69 : United States
91.225.248.133 : Ireland
216.58.212.234 : United States

displaying listening ports

mysqld TCP *:3306 (LISTEN)
com.avast TCP 127.0.0.1:12080 (LISTEN)
com.avast TCP [::1]:12080 (LISTEN)
com.avast TCP 127.0.0.1:12110 (LISTEN)
com.avast TCP [::1]:12110 (LISTEN)
com.avast TCP 127.0.0.1:12143 (LISTEN)
com.avast TCP [::1]:12143 (LISTEN)
com.avast TCP 127.0.0.1:12995 (LISTEN)
com.avast [::1]:12995 (LISTEN)
com.avast 127.0.0.1:12993 (LISTEN)
com.avast [::1]:12993 (LISTEN)
Google TCP 127.0.0.1:34013 (LISTEN)

This may be useful to check if you are connected to north-korea! ;-)

Undercurrent answered 3/7, 2017 at 10:19 Comment(1)
Great! Just update it to ipstack (because freegeoip does not exist anymore) and use jp instead of grep for easier parsing of json.Myrlemyrlene
D
2

This is a good way on macOS High Sierra:

netstat -an |grep -i listen
Delldella answered 15/8, 2018 at 17:49 Comment(1)
That's quite right! The accepted answer actually is the right way ... netstat on mac os x doesn't show the pid to port mapping.Delldella
T
2

Inspired by user Brent Self:

lsof -i 4 -a | grep LISTEN

Tramline answered 1/1, 2019 at 0:55 Comment(0)
A
2

For macOS I use two commands together to show information about the processes listening on the machine and process connecting to remote servers. In other words, to check the listening ports and the current (TCP) connections on a host you could use the two following commands together

1. netstat -p tcp -p udp 

2. lsof -n -i4TCP -i4UDP 

Thought I would add my input, hopefully it can end up helping someone.

Andonis answered 13/1, 2019 at 19:24 Comment(0)
R
1

Just a slight improvement on Michał Kalinowski's answer (I don't have enough reputation to leave a comment there): if you are trying to find the process listening on a port numbered 255 and below, the grep command might print lines related to the IP address, and which do not correspond to the desired result. For a port with any number, the grep command might also erroneously match the device's MAC address or PID. To improve on this, I suggest changing the command to grep --color ":$1 "

Rillings answered 20/9, 2022 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.