Simple netcat-like TCP Server or client

 

Need to have a process listening on some port to test your firewall rules? Instead of using a netcat or ncat, here’s a very simple Powershell implementation of this ncat/netcat feature:

function Wait-OnPort ($port) {
$endpoint = new-object System.Net.IPEndPoint ([ipaddress]::any,
$port)
$listener = new-object System.Net.Sockets.TcpListener $endpoint
$listener.start()
$listener.AcceptTcpClient() # wait until somebody connect
$listener.stop()
}

If you need a TCP Client, the code is very straightforward:

$t = New-Object System.Net.Sockets.TcpClient("servernameorIPAddress",port)
#port is not open, you get an exception
New-Object : Exception calling ".ctor" with "2" argument(s): "No connection could be made because the target machine actively refused it 10.254.212.81:666"
At line:1 char:16
+ $t = New-Object <<<<  System.Net.Sockets.TcpClient("servernameorIPAddress",port)
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

#port is open, you get nothing
$t.Close()