windows - PowerShell Function to check whether certain port is in LISTENING state on localhost

07
2014-07
  • utrecht

    Introduction

    Aim: to check whether a port is in LISTENING state on localhost by using a PowerShell function

    The following command:

    New-Object Net.Sockets.TcpClient.Connect("127.0.0.1",10389)

    results in:

    PS C:\Windows\system32> New-Object Net.Sockets.TcpClient.Connect("127.0.0.1",10389)
    At line:1 char:33
    + New-Object Net.Sockets.TcpClient.Connect("127.0.0.1",10389)
    +                                 ~
    Unexpected token ')' in expression or statement.
        + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : UnexpectedToken
    
    PS C:\Windows\system32>
    

    Question

    Which PowerShell Function could be used to check whether a certain port is in LISTENING state on localhost?

  • Answers
  • techie007

    If you're using PowerShell v3.0+, then instead of trying to connect to the port to determine the state, you can simply use Get-NetTCPConnection:

    Get-NetTCPConnection -State Listen

    To me this is more accurate as it's reading the status of the port on the computer. Using a connection to test can make it seem like it's not "LISTENING" when it is, if a firewall or alike gets in the way or something.

  • Tim Ferrill

    First create and store the connection:

    $connection = (New-Object Net.Sockets.TcpClient)
    $connection.Connect("127.0.0.1",10389)
    

    Then check if it's connected

    if ($connection.Connected) {
        "We're connected"
        }
    

    Or as suggested by Colyn1337

    Try {
        $connection = (New-Object Net.Sockets.TcpClient)
        $connection.Connect("127.0.0.1",10389)
        "Connected"
        }
    Catch {
        "Can't Connect"
        }
    
  • Colyn1337

    I had tried to add this to techie's answer, so this is an expansion of his. You can fine tune the output like so:

    Get-NetTCPConnection -State Listen | Where-Object {$_.LocalAddress -eq "192.168.56.1" -and $_.LocalPort -eq "139"}
    

    That would return an array of data if it were listening on that port. If there is no listener, it returns null and therefore no need for error handling.


  • Related Question

    What is the port that is used by localhost?
  • Ieyasu Sawada

    I'm using WAMP server. What is the port that is used by this application?

    I want to share the contents of it to others.


  • Related Answers
  • Peter Mortensen

    Be specific your question. WAMP is Window, Apache, MySQL and PHP.

    Apache uses port 80 and MySQL uses port 3306 (on Windows).

    How do you want to share? Via a web browser or a Windows network?