0

I am currently working on a program that establishes TCP and UDP connections between different ports on my computer (thereby simulating a real system). When I kill the main process running, the TCP connections remain open on my computer. So far I have been killing them manually by running netstat -ano | findstr PID :8080 (assuming 8080 was the port), to get the PIDs and then running taskkill //PID $pidnum //F to kill the process. As I am doing this on a few ports I wanted to right a bash script that would do this for me.

To write this script I want to loop through the different ports I am using and save the PIDS in an array and then loop through this array and kill each process. However, I am having difficulty extracting only the PID from the netstat return. The return looks something like this:

Proto Local Address Foreign Address State PID TCP 127.0.0.1:50065 0.0.0.0:0 LISTENING 5384 TCP [::1]:50057 [::]:0 LISTENING 6788 

I have tried netstat -ano | findstr "PID :8080" | awk '{print $7}' which should be the PID column but it only returns the column header (PID) but not the actual PID numbers. Any ideas?

Note: I am using the git bash terminal if that makes a difference and as such by default it does not come with commands like lsof.

2
  • Why don't you change the main process so it catches the signal you use to kill it, and it kills all the child processes? Commented Jan 3, 2020 at 1:17
  • Good suggestion - i'll look into that. For now though your answer below works great! Thanks! Commented Jan 3, 2020 at 2:13

1 Answer 1

3

I'm not familiar with the findstr command, but there's no need to use another command to search for matching lines, as awk can do that by itself.

netstat -ano | awk '$1 == "TCP" && $2 ~ /:8080/ { print $5 }' 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.