PowerShell: How To Test A Server Ephemeral Port

# Setup a listening port on server
# This session will automatically terminates after a number of test counts

function initTestEpheralPort{
  param(
    $port=59848,
    $testCount=3
  )
  $cmdlet="(new-object Net.Sockets.TcpClient).Connect('$env:computername', $port)"
  write-host "$env:computername is now listening on port $port"
  write-host "Please run this function at the client side:`r`n$cmdlet"
  $listener=[System.Net.Sockets.TcpListener]$port;
  $listener.Start();
  while($testCount) 
  {    
      $clientAccepted=$listener.AcceptTcpClient();
      if($clientAccepted){
          write-host "$((netstat -ano -p tcp|select-string "$port"|out-string))"
          $testCount--;
          Write-Host "Connection test $testCount remains!";   
      }
      $clientAccepted.Close();
      if(!$testCount){
          # Stop listening on the server
          $listener.Stop();
          write-host "Tests have completed."  
      }
  }
}

initTestEpheralPort 59848
# Test reachability from a client machine
$server='nameOrIpHere'
$port=59848
(new-object Net.Sockets.TcpClient).Connect($server, $port)

Leave a Reply

Your email address will not be published. Required fields are marked *