I want to write a script to test my server and I want to be able to connect and disconnect thousands of users in a script that uses nc, what I came up with is:
echo "Test" | nc localhost <port> &
NCPID=$!
sleep 1
kill -kill $NCPID
But I'd like to remove the sleep 1 and still get the netcat connection closed after "Test" was echoed, how could I do that ?
Check -w option for netcat:
-w timeout If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. The -w flag has no
effect on the -l option, i.e. nc will listen forever for a connection,
with or without the -w flag. The default is no timeout.
echo "Test" | nc localhost <port> -w 1 &
Is it possible to listen to a port continuously?
I listen for incoming tcp notifications with following command
sudo nc -l -p 999
But as soon as notification arrives I have to restart listen with same command. Is it possible to listen to port without having to restart command when notifications arrives until user decides to abort listen?
Sorta outdated question, but came up first on my Google search.
In order for netcat not to shutdown as soon as the first connection is received, you can add the -k option.
From the man:
-k Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.
Src: https://superuser.com/a/708133/410908
Solved with a simple bash script
#!/bin/bash
#Make Sure Script Is Ran As Root
if [ $(id -u) != 0 ]; then
echo; echo -e "\e[1;31mScript must be run as sudo. Please Type \"sudo\" To Run As Root \e[0m"; echo
exit 1
fi
echo "Enter port to listen"
read portL
while true;
do
nc -l -p $portL
done
exit 0
Thanks dreamlax for the tip!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 11 months ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
On MacOSX, I'm using Packer to build a Vagrant box so I need to continually bring it up and tear it down. I'm attempting to 'vagrant up', and receive the standard error because the port is in use:
"Vagrant cannot forward the specified ports on this VM, since they would collide with some other application that is already listening on these ports. The forwarded port to 8080 is already in use on the host machine."
The solution seems simple enough: I just need to identify the process that is holding port 8080 open and kill that process, right?. It's not that easy.
If I run the command:
nmap localhost -p 8080
I receive the following output:
PORT STATE SERVICE
8080/tcp open http-proxy
If I run the following command:
top -o prt
The highest port in use in 1360
If I run the following command:
netstat -tulpn | grep :8080
I receive:
netstat: n: unknown or uninstrumented protocol
If I run the following command:
lsof -i :8080
I receive no output
If I restart my computer, the port is now available and I can now 'vagrant up'.
How can I kill whatever process is using port 8080 so that I can vagrant up without restarting my computer?
This might help
lsof -n -i4TCP:8080
The PID is the second field in the output.
Or try:
lsof -i -P
Fast and quick solution:
lsof -n -i4TCP:8080
PID is the second field. Then, kill that process:
kill -9 PID
Less fast but permanent solution
Go to /usr/local/bin/ (Can use command+shift+g in finder)
Make a file named stop. Paste the below code in it:
#!/bin/bash
touch temp.text
lsof -n -i4TCP:$1 | awk '{print $2}' > temp.text
pidToStop=`(sed '2q;d' temp.text)`
> temp.text
if [[ -n $pidToStop ]]
then
kill -9 $pidToStop
echo "Congrates!! $1 is stopped."
else
echo "Sorry nothing running on above port"
fi
rm temp.text
Save this file.
Make the file executable chmod 755 stop
Now, go to terminal and write stop 8888 (or any port)
In case above-accepted answer did not work, try below solution.
You can use it for port 8080 or for any other ports.
sudo lsof -i tcp:3000
Replace 3000 with whichever port you want. Run below command to kill that process.
sudo kill -9 PID
PID is process ID you want to kill.
Below is the output of commands on mac Terminal.
Use the following command:
lsof -n -i4TCP:8080 | awk '{print$2}' | tail -1 | xargs kill -9
The process id of port 8080 will be picked and killed forcefully using kill -9.
I needed to kill processes on different ports so I created a bash script:
killPort() {
PID=$(echo $(lsof -n -i4TCP:$1) | awk 'NR==1{print $11}')
kill -9 $PID
}
Just add that to your .bashrc and run it like this:
killPort 8080
You can pass whatever port number you wish
To script this:
pid=$(lsof -ti tcp:8080)
if [[ $pid ]]; then
kill -9 $pid
fi
The -t argument makes the output of lsof "terse" which means that it only returns the PID.
sudo lsof -i:8080
By running the above command you can see what are all the jobs running.
kill -9 <PID Number>
Enter the PID (process identification number), so this will terminate/kill the instance.
I needed to run this command
sudo lsof -i :80 # checks port 8080
Then i got
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
acwebseca 312 root 36u IPv4 0x34ae935da20560c1 0t0 TCP 192.168.1.3:50585->104.25.53.12:http (ESTABLISHED)
show which service is using the PID
ps -ef 312
Then I got this
UID PID PPID C STIME TTY TIME CMD
0 312 58 0 9:32PM ?? 0:02.70 /opt/cisco/anyconnect/bin/acwebsecagent -console
To uninstall cisco web security agent run
sudo /opt/cisco/anyconnect/bin/websecurity_uninstall.sh
credits to: http://tobyaw.livejournal.com/315396.html
It can be Cisco AnyConnect.
Check if /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist exists. Then unload it with launchctl and delete from /Library/LaunchDaemons
You can also use the Activity Monitor to identify and quit the process using the port.
Run: nmap -p 8080 localhost (Install nmap with MacPorts or Homebrew if you don't have it on your system yet)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00034s latency).
Other addresses for localhost (not scanned): ::1
PORT STATE SERVICE
8080/tcp open http-proxy
Run: ps -ef | grep http-proxy
UID PID PPID C STIME TTY TIME CMD
640 99335 88310 0 12:26pm ttys002 0:00.01 grep http-proxy"
Run: ps -ef 640 (replace 501 with your UID)
/System/Library/PrivateFrameworks/PerformanceAnalysis.framework/Versions/A/XPCServices/com.apple.PerformanceAnalysis.animationperfd.xpc/Contents/MacOS/com.apple.PerformanceAnalysis.animationperfd
Port 8080 on mac osx is used by something installed with XCode SDK
try netstat
netstat -vanp tcp | grep 3000
if your netstat doesn't support -p , use lsof
sudo lsof -i tcp:3000
For Centos 7 use
netstat -vanp --tcp | grep 3000
After referring to the solution of #voutasaurus. I wrote this utility to simplify the process of killing all the processes that are running on the port.
killProcessesUsing3000 () {
pid=$(lsof -ti :3000) # The -t argument makes the output of lsof "terse" (Brief) which means that it only returns the PID.
# PID contains process processes that run on the 3000 port. In new lines if they are multiples
for num ($=pid) {
echo $num
kill -9 $num
}
}
#Alias
alias kill3000="killProcessesUsing3000"
For me this worked
Open your mac terminal
kill $(lsof -t -i:8080)
Explanation:
lsof -t returns the PID and passes that to kill.
I tried many of the above and they didn't work for me.
After many hours, I found this one liner:
# kill 8080
alias nuke88="lsof -i tcp:8080 | grep LISTEN | awk '{print \$2}' | xargs kill"
# kill 3000
alias nuke3k="lsof -i tcp:3000 | grep LISTEN | awk '{print \$2}' | xargs kill"
I'm trying to kill the process associated with port 161 (SNMP) on OS X.
I tried to get the process ID associated with this port using netstat and lsof but none of these seem to list PIDs:
$ netstat -an | grep 161
udp4 0 0 *.161 *.*
$ netstat -anp udp | grep 161
udp4 0 0 *.161 *.*
lsof -i :161
SNMP is UDP, not TCP. It does't "listen" because there is no such concept for UDP sockets.
Look for the process by its name or process ID instead.
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?
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.
Prepend sudo (followed by a space) if you need information on ports below #1024.
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
Up to macOS 13 Ventura, 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.
You can also use:
sudo lsof -i -n -P | grep TCP
This works in Mavericks.
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:
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)
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, ex: 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 items used:
-n suppress the host name
-i for IPv4 and IPv6 protocols
-P omit port names
-a [over netstat] for all sockets
-n [over netstat] 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
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
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
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.
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.
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.
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:
lsof -n -i | awk '{ print $1,$9; }' | sort -u
This displays who's doing what. Remove -n to see hostnames (a bit slower).
This did what I needed.
ps -eaf | grep `lsof -t -i:$PORT`
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! ;-)
This is a good way on macOS High Sierra:
netstat -an |grep -i listen
Inspired by user Brent Self:
lsof -i 4 -a | grep LISTEN
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.
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 "