How to find running processes and their port number

February 10, 2011

18 comments

The netstat command line utility displays protocol statistics and current TCP/IP network connections. If we want to display the associated process identifier (PID) of each process we add the -o parameter.

image

To filter the result we need to pipe to the Find utility and again, the result is text!. In PowerShell we can get the same information with the following command, however the process PID is missing and the connections in LISTENING state are not included by default.

PS > [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpConnections()

With the Get-NetworkStatistics function we can get the same information but each returned connection is an object. Get-NetworkStatistics parses only TCP/UDP connections (entries that starts with ‘[::' are ignored). Each connection is divided into two columns. For example, if the 'Local Address' column has a value of '0.0.0.0:80' the IP address will be shown in the LocalAddress property (e.g 0.0.0.0)  and the port number in the LocalPort property (e.g 80). The name of each process is also added to the result. This should make filtering much more easier when we pipe the result to the Where-Object cmdlet, allowing us to filter on any property of a connection.

UPDATE1: Added support for IPv6 connections. @xcud and surveyor, thanks for the input!
UPDATE2: Per @xcud request (see comment below) I published an extended version of the function HERE.

 

function Get-NetworkStatistics
{
    $properties = 'Protocol','LocalAddress','LocalPort'
    $properties += 'RemoteAddress','RemotePort','State','ProcessName','PID'

    netstat -ano | Select-String -Pattern '\s+(TCP|UDP)' | ForEach-Object {

        $item = $_.line.split(" ",[System.StringSplitOptions]::RemoveEmptyEntries)

        if($item[1] -notmatch ‘^\[::')
        {           
            if (($la = $item[1] -as [ipaddress]).AddressFamily -eq ‘InterNetworkV6′)
            {
               $localAddress = $la.IPAddressToString
               $localPort = $item[1].split(‘\]:’)[-1]
            }
            else
            {
                $localAddress = $item[1].split(‘:’)[0]
                $localPort = $item[1].split(‘:’)[-1]
            } 

            if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq ‘InterNetworkV6′)
            {
               $remoteAddress = $ra.IPAddressToString
               $remotePort = $item[2].split(‘\]:’)[-1]
            }
            else
            {
               $remoteAddress = $item[2].split(‘:’)[0]
               $remotePort = $item[2].split(‘:’)[-1]
            } 

            New-Object PSObject -Property @{
                PID = $item[-1]
                ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
                Protocol = $item[0]
                LocalAddress = $localAddress
                LocalPort = $localPort
                RemoteAddress =$remoteAddress
                RemotePort = $remotePort
                State = if($item[0] -eq ‘tcp’) {$item[3]} else {$null}
            } | Select-Object -Property $properties
        }
    }
}

Get-NetworkStatistics | Format-Table

image

To get all processes running on a local port 80:

image

Or find a connection information by filtering on ProcessName:

image















Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

18 comments

  1. OldDogFebruary 10, 2011 ב 17:47

    Great post and very timley, for me.
    I need to be able to check two Ports on a server to make sure that they are open as opart of troubleshooting OpsWare (HPSA). They are ports 1002 and 3001.

    I ran you function and got this:

    Protocol LocalAddress LocalPort RemoteAddres RemotePort State
    s
    ——– ———— ——— ———— ———- —–
    TCP 0.0.0.0 1002 0.0.0.0 0 LISTENING

    Port 3001 returned nothing.
    Should I assume that it is closed or is it just not active?

    In any event thanks for this.

    Reply
  2. ScriptFanaticFebruary 10, 2011 ב 18:00

    It could be that at the time you ran the command there was no process listening to port 3001 or that it’s not active. You can also use another method to check if a port is open on a target machine, check the Test-TcpPort function here:

    http://halr9000.com/article/418

    Reply
  3. surveyorFebruary 10, 2011 ב 23:16

    It does not work for adapters with IPV6-addresses. Maybe a regex-filter would be more flexible than the splits?

    TCP [fe80 50219 [fe80 3587 HERGESTELLT svchost 1132

    Reply
  4. ScriptFanaticFebruary 11, 2011 ב 09:30

    surveyor, I updated the function and added support for IPv6.

    Reply
  5. xcudMarch 2, 2011 ב 00:09

    This is one of my favorite powershell functions of late. FWIW, this would even more useful if it took parameter input; i.e. processname (with wildcard support), address, or port

    Usage:
    Get-NetworkStatistics -ProcessName skype
    Get-NetworkStatistics -Address 192.168.1.1
    Get-NetworkStatistics -Port 80

    Maybe with a default to ProcessName:
    Get-NetworkStatistics skype

    Reply
  6. redcodeDecember 20, 2011 ב 12:28

    when i try to run your function, it does not works.. :(
    i am tring in administrator powershell…
    for example…

    ps c:\swsetup> .\Get-NetworkStatistics -ProcessName *md – Protocol tcp
    it does anything…
    ??
    ps c:\swsetup>Get-NetworkStatistics -ProcessName *md – Protocol tcp

    it is same

    Reply
  7. ScriptFanaticDecember 20, 2011 ב 13:48

    If you saved the function in a script file then you need to dot-source the file first (loads the function into memory) and then you can execute it:

    # dot source the script file
    PS> . c:\Get-NetworkStatistics.ps1

    # call the function
    PS > Get-NetworkStatistics -ProcessName *md – Protocol tcp

    Reply
  8. KWJanuary 5, 2012 ב 00:30

    How can I run this against a remote computer?

    Reply
  9. ScriptFanaticJanuary 5, 2012 ב 10:05

    You can’t. netstat works only locally and doesn’t support remote computers. However, if you have PowerShell Remoting enabled on the target computer then you can use Invoke-Command cmdlet to execute it on the remote machine.

    Reply
  10. Mike LewisMay 2, 2012 ב 19:22

    Shay, This is really useful. Thanks much for posting it!

    Reply
  11. Cookie MonsterOctober 16, 2012 ב 15:36

    For anyone interested in running this against remote computers, I integrated Shay’s function with some ideas from this script:

    gallery.technet.microsoft.com/…/Netstat-on-a-remote-58e1aa77

    I’m sure there are more elegant ways to do this, but it gets the job done.

    The modified function can be found here:  gallery.technet.microsoft.com/…/Get-NetworkStatistics-66057d71

    There are a few changes:

    -Added a computername parameter, tempFile parameter, and removed the port parameter position.

    -Shay’s code remains essentially intact, but when a remote computer is specified, WMI is used to create a process to run netstat on the remote computer and send results to a file on that computer.  The results file is collected and run against Shay’s code.

    Thanks for the help Shay!  I find myself using your solutions quite often : )

    Reply
  12. -January 3, 2013 ב 01:45

    This website is great. I like it.(www.linkspirit.net)N_X_D_S.

    Reply
  13. MikeFebruary 13, 2013 ב 12:47

    Getting info based solely on State doesn’t appear to work:

    PS C:\Windows\System32\WindowsPowerShell\v1.0> Get-NetworkStatistics -State LISTENING
    Get-NetworkStatistics : Cannot validate argument on parameter ‘State’. The argument “LISTENING” does not belong to the
    set “*,Closed,CloseWait,Closing,DeleteTcb,Established,FinWait1,FinWait2,LastAck,Listen,SynReceived,SynSent,TimeWait,Unk
    nown” specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
    At line:1 char:29
    + Get-NetworkStatistics -State <<<< LISTENING
    + CategoryInfo : InvalidData: (:) [Get-NetworkStatistics], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Get-NetworkStatistics

    Reply
  14. PowellMarch 25, 2013 ב 10:44

    As an example if you made up my mind that fixed life insurance precisely what you need, I recommend looking into a Guaranteed General Life Rrnsurance plan policy, quantities lifetime contract having a
    warranty that the policy will last your whole life.
    This really costs less than whole life insurance coverage and benefits many
    those who would for example , some long-term life car insurance.

    Reply
  15. EdwardMarch 27, 2013 ב 18:51

    Home Remodeling Sweepstakes is open to Ohio residents only, and
    will not fade from years of sun exposure. Through sites
    like Living Social, if you do more and go further than what
    is possible on an iPhone.

    Reply
  16. RaderMarch 27, 2013 ב 19:15

    I just remember a visit to your local building inspector to understand what permits and building requirements are necessary for
    your project can be found that addresses the death of Dawn.

    One way to determine high quality originality, compared to
    natural products it still had some issues to work on weekends.

    Reply
  17. SimonAugust 23, 2013 ב 05:07

    The Extreme Q has almost all of the advantages that the Volcano vaporizer has and is asimilar type of hot air blowing table top vaporizer.
    I would suggest as he does you go for the Mini PCC starter kit ($79.
    Humidifiers put a certain percentage of moisture into the air depending on
    what you set it at.

    Reply
  18. ReedAugust 29, 2013 ב 16:54

    Therefore, plumbing problems tend to be shocking and totally unexpected.
    Our world has transformed considerably and with the coming of
    internet individuals are required to use time
    and effort in browsing online for excellent specialists.

    One aspect you should be very careful at is the furniture of your future
    renovated rooms.

    Reply