0
try
{
  $tcp = new-object System.Net.Sockets.TcpClient

  $tcp.ReceiveTimeout = 500
  $tcp.SendTimeout = 500

  $tcp.Connect('127.0.0.1',80)
  Write-Host "Connection possible!"
  $tcp.close()
}
catch
{
    Write-Host "Cannot connect!"
    $_.Exception.Message
}

Measure-Command - 21 seconds (always 21!)

If $tcp.Connect('127.0.0.1',80,$Null)

Measure-Command - 10 milliseconds

Why?

I know that there should be no $Null param but why is it fast with it ?

Endorphinex
  • 23
  • 2
  • 11
Igor Kuznetsov
  • 421
  • 1
  • 6
  • 15
  • $tcp.Connect take two parameters not three https://msdn.microsoft.com/en-us/library/d7ew360f(v=vs.110).aspx. With three parameters raise exception:Cannot connect! Cannot find an overload for "Connect" and the argument count: "3". It take 1 second to run with success connection in my machine with 2 parameters. – M.Hassan Oct 14 '16 at 16:40

2 Answers2

3

I know that there should be no $Null param but why is it fast with it ?

Because your code is broken.

try 
{

}
catch
{
}

is catching every possible error, and hiding the error messages.

Your first code, the error is a genuine TCP connection which timed out after a ~30 second wait, and the connection really has failed.

Your second code, the error is "Cannot find an overload for Connect which takes 3 parameters" - but you hide the error and wrongly print 'cannot connect' instead. This is misleading you. It's not faster, it's broken.


The send and receive timeouts are not for connections, they are timeouts for the methods to sending and receive data. There is no way to change the connection timeout with the .connect() method, you need to make an asynchronous connection without your own timeout to do that.

e.g. How to set the timeout for a TcpClient? and How to configure socket connect timeout (both C#, but still .Net and the ideas are applicable to PowerShell).

And this https://superuser.com/questions/805621/test-network-ports-faster-with-powershell which has an answer for PowerShell

Community
  • 1
  • 1
TessellatingHeckler
  • 27,511
  • 4
  • 48
  • 87
0

$tcp.Connect('127.0.0.1',80,$Null) throws an exception Cannot find an overload for "Connect" and the argument count: "3". Read more here: MDSN Documentation

Endorphinex
  • 23
  • 2
  • 11