Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a TCP port is open without connecting to it

I've been asked to convert a bash script which uses nc -z, to PowerShell.

This site tells me that nc -z tests whether a port is open "without connecting to it". Is there some way to do that using .Net?

Additional Info

Normally to test if a port is open I'd .Net's TcpClient to create a connection; and if it connects I report all as well. MVE below:

$isConnected = $false
$client = New-Object -TypeName 'System.Net.Sockets.TcpClient'
try {
    $client.Connect($host, $port)
    $isConnected = $client.Connected
    $client.GetStream().Close(); # handle bug in .net 1.1
    $client.Close();
} catch {
    $isConnected = $false
} finally {
    if ($client.Dispose) {$client.Dispose()} # dispose method not available in all versions, so check before calling
}

However, whilst that sends no data, it does connect.

It could be that the description of nc -z is misleading / that it just means without sending data... I've not been able to find confirmation either way.

Side node

Based on a couple of recent responses I'll point out that Test-NetConnection essentially uses the same TcpClient approach as mentioned above, so does "connect". Also it's not available in PS2 / only comes into play in PSv4 in Windows 8 & above. That said, it's worth a mention for anyone who doesn't have the unique requirements mentioned in this post.

like image 487
JohnLBevan Avatar asked Oct 10 '19 09:10

JohnLBevan


1 Answers

Using Test-NetConnection

Test-NetConnection -ComputerName $host -Port $port

Output looks like this:

ComputerName     : [computername]
RemoteAddress    : [remoteipaddress]
RemotePort       : 80
InterfaceAlias   : Ethernet 2
SourceAddress    : [sourceipaddress]
TcpTestSucceeded : True

Test-NetConnection Documentation

Using Tcp Client Class (.Net):

 New-Object System.Net.Sockets.TcpClient($ip, $port)

Output:

Client              : System.Net.Sockets.Socket
Available           : 0
Connected           : True
ExclusiveAddressUse : False
ReceiveBufferSize   : 65536
SendBufferSize      : 64512
ReceiveTimeout      : 0
SendTimeout         : 0
LingerState         : System.Net.Sockets.LingerOption
NoDelay             : False

Tcp Client Documentation

like image 75
Rob0tScience Avatar answered Nov 13 '22 12:11

Rob0tScience