Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase timeout for System.Net.Sockets.Socket connect

I need to allow for connections to a FTP server using System.Net.Sockets.Socket to take a long time - at least 30 seconds but possibly more. This code always returns as signalled but not connected after 20 seconds which is apparently the internal default:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("128.0.0.1", 99, null, null);
bool signalled = result.AsyncWaitHandle.WaitOne(60000, true);
like image 876
Bert Avatar asked Oct 20 '25 01:10

Bert


1 Answers

Old question, but we had the same problem, so I'll post our solution here.

The WaitOne timeout can be used to force a lower timeout than the system default, but if you want to increase the timeout (i.e. to more than 20 seconds in your case) you have to change the TCP settings of the underlying operating system.

We ran into this problem on Windows, where we encountered a hard timeout limit on 21 seconds. To change this, you can use the following PowerShell command (running the PowerShell prompt as admin):

Set-NetTCPSetting -SettingName InternetCustom -MaxSynRetransmissions 4

The default value is 2, which yields an effective TCP connection timeout of about 21 seconds. A value of 3 increases the timeout to about 40 seconds, and 4 to about 90 seconds. More info can be found here.

For Linux, check out this article: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout

like image 182
Erik Öjebo Avatar answered Oct 21 '25 14:10

Erik Öjebo