How to Do Like "Netstat -P", But Faster

How to do like netstat -p, but faster?

Take a look at this answer, where various methods and programs that perform socket to process mappings are mentioned. You might also try several additional techniques to improve performance:

  1. Caching the file descriptors in /proc, and the information in /proc/net. This is done by the programs mentioned in the linked answer, but is only viable if your process lasts more than a few seconds.
  2. You might try getpeername(), but this relies you knowing of the possible endpoints and what processes they map to. Your questions suggests that you are connecting sockets locally, you might try using Unix sockets which allow you to receive the credentials of a peer when exchanging messages by passing SO_PASSCRED to setsockopt(). Take a look at these examples (they're pretty nasty but the best I could find).

    • http://www.lst.de/~okir/blackhats/node121.html
    • http://www.zanshu.com/ebook/44_secure-programming-cookbook-for-c-and-cpp/0596003943_secureprgckbk-chp-9-sect-8.html
  3. Take a look at fs/proc/base.c in the Linux kernel. This is the heart of the information given by the result of a readlink on a file descriptor in /proc/PID/fd/FD. A significant part of the overhead is the passing of the requests up and down the VFS layer, the numerous locking that occurs on all the kernel data structures that provide the information given, and the stringyfying and destringyfying at the kernel and your end respectively. You might adapt some of the code in this file to generate this information without many of the intermediate layers, in particular minimizing the locking to once per process, or simply once per scan of the entire data set you're after.

My personal recommendation is to just brute force it for now, ideally traverse the processes in /proc in reverse numerical order, as the more recent and interesting processes will have higher PIDs, and return as soon as you've located the results you're after. Doing this once per incoming connection is relatively cheap, it really depends on how performance critical your application is. You'll definitely find it worthwhile to bypass calling netstat and directly parse the new connection from /proc/net/PROTO, then locate the socket in /proc/PID/fd. If all your traffic is localhost, just switch to Unix sockets and get the credentials directly. Writing a new syscall or proc module that dumps huge amounts of data regarding file descriptors I'd save for last.

Netstat continuous refresh (watch changes the output)

netstat -c

may help you if i've not misunderstood your problem. -c stands for --continuous.

EDIT:
there you go:

watch -n 30 "netstat -ntu | awk '{print \$5}' | cut -d: -f1 | sort | uniq -c | sort -n"

I've added a \ before $.

How do I kill the process currently using a port on localhost in Windows?

Step 1:

Open up cmd.exe (note: you may need to run it as an administrator, but this isn't always necessary), then run the below command:

netstat -ano | findstr :<PORT>

(Replace <PORT> with the port number you want, but keep the colon)

Sample Image

The area circled in red shows the PID (process identifier). Locate the PID of the process that's using the port you want.

Step 2:

Next, run the following command:

taskkill /PID <PID> /F

(No colon this time)

Sample Image

Lastly, you can check whether the operation succeeded or not by re-running the command in "Step 1". If it was successful you shouldn't see any more search results for that port number.

How to retrieve the result of netstat command

You can start with this code

int main() {
char buf[10000];
FILE *p = _popen("netstat -a", "r");
std::string s;
for (size_t count; (count = fread(buf, 1, sizeof(buf), p));)
s += string(buf, buf + count);
cout<<s<<endl;
_pclose(p);
}

What port is a given program using?

netstat -b -a lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista.

I usually add -n as well to make it a little faster, but adding -b can make it quite slow.

Edit: If you need more functionality than netstat provides, vasac suggests that you try TCPView.

Kill a Process by Looking up the Port being used by it from a .BAT

Here's a command to get you started:

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P

When you're confident in your batch file, remove @ECHO.

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P

Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5 instead of tokens=4.

How this works

FOR /F ... %variable IN ('command') DO otherCommand %variable...

This lets you execute command, and loop over its output. Each line will be stuffed into %variable, and can be expanded out in otherCommand as many times as you like, wherever you like. %variable in actual use can only have a single-letter name, e.g. %V.

"tokens=4 delims= "

This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -a -n -o

Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)

^|

This takes the output of the first command or program (netstat) and passes it onto a second command program (findstr). If you were using this directly on the command line, instead of inside a command string, you would use | instead of ^|.

findstr :8080

This filters any output that is passed into it, returning only lines that contain :8080.

TaskKill.exe /PID <value>

This kills a running task, using the process ID.

%%P instead of %P

This is required in batch files. If you did this on the command prompt, you would use %P instead.



Related Topics



Leave a reply



Submit