Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether port is open in Powershell

I do not have telnet command in my system.

However my system is installed with Windows 10, so there must be a way to check whether particular port is open or not in a remote system. That particular remote system is accessible I had checked with ping command.

So here is my simple question,- how to check whether particular port is open or not using powershell.

Command netstat could brief for local system service & port and particular protocol either UDP or TCP is up & runnning. As I do not have telnet I need this to be sorted out and tackled by powershell. Any advise and suggestion are welcome.

like image 613
Dev Anand Sadasivam Avatar asked May 02 '17 07:05

Dev Anand Sadasivam


2 Answers

Test-NetConnection ###.###.###.### -Port ##
like image 124
Brandon Lanczak Avatar answered Oct 11 '22 14:10

Brandon Lanczak


You can use the following to try and open a port, if no error is returned the port is open:

$ipaddress = ""
$port = ""
$tcpClient = new-object Net.Sockets.TcpClient
$tcpClient.Connect("$ipaddress", $Port)
$tcpClient.Dispose()

Here's a more complete example, which returns true/false which is the way that Test-Path works:

function Test-Port
{
    param
    (
        $Address,
        $Port
    )
    $tcpClient = new-object Net.Sockets.TcpClient
    try
    {
        $tcpClient.Connect("$Address", $Port)
        $true
    }
    catch
    {
        $false
    }
    finally
    {
        $tcpClient.Dispose()
    }
}

Test-Port -Address localhost -Port 80
Test-Port -Address localhost -Port 81 

Depending on the version of Powershell/Windows you are using Test-NetConnection may be more appropriate.

like image 7
David Martin Avatar answered Oct 11 '22 15:10

David Martin