How to View Thread Id of a Process Which Has Opened a Socket Connection

How to view thread id of a process which has opened a socket connection?

As MarkR suggested, you need to use strace from startup:

strace -fp <pid>

The above command will show you per thread system calls like open(), read(), recv() etc, along with the descriptors used:

[pid 428] close(36) 

Once you isolated the thread, you may attach to the process and find out the exact thread with

gdb attach <pid>

Or, if you have thread names set in your process, use

ps -eL

to find out the thread's friendly name.

How do I find out what process Id and thread id / name has a file open

Here's some pseudocode that will protect the resource across threads:

while (true)
{
Read a packet from a socket (with data in it to add to the file)
lock (static locker object)
{
Open a file
Writes data to it
Close a file
}
}

in the C# world, the static locker object is usually declared at the class level thusly:

private static readonly object locker = new object();

I would also recommend using the using keyword to protect the file resource if the statements between the opening and closing of the file throws an exception. Re-done pseudocode:

while (true)
{
Read a packet from a socket (with data in it to add to the file)
lock (static locker object)
{
using (Open a file)
{
Writes data to it
} // leaving the using block will close the file
}
}

Is it possible to get the thread Id of a process that is listening to a Port in Windows?

hook socket, bind, listen, accept (and WSAXxx equivalents) and call GetCurrentThreadId() in the hook handlers. you can leverage e.g. MS Detours, EasyHook, or MHook etc to implement your handlers.

How do I find out which process is listening on a TCP or UDP port on Windows?

PowerShell

TCP

Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess

UDP

Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess

cmd

 netstat -a -b

(Add -n to stop it trying to resolve hostnames, which will make it a lot faster.)

Note Dane's recommendation for TCPView. It looks very useful!

-a Displays all connections and listening ports.

-b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.

-n Displays addresses and port numbers in numerical form.

-o Displays the owning process ID associated with each connection.



Related Topics



Leave a reply



Submit