This article was previously published under Q173619
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
The Winsock control will get an error after a Connect method is called ifthe same local port has been used within the past four minutes.
The Windows socket control does not have the ability to set the socketoption SO_REUSEADDR. This option allows the socket to be bound to anaddress that is already in use.
When you close the handle to a socket, some additional negotiation goes onbetween the client and the server. The socket will wait for up to two timesthe maximum time that windows would wait to receive an acknowledgement fromthe other end of the socket that closed the port. By default, this optionis set to two minutes. Therefore, Windows may wait up to four minutesbefore the port is actually released.
This makes that specific port unavailable until it is actually released.
The only workaround is to not use a specific local port. If you set theLocalPort property to Zero, Winsock will pick a random local port for youand use it until a Close method is called on the WinSock Control.
This behavior is by design.
Setting the LocalPort property of the socket to Zero, will cause Windows topick a random port.
To do this, place the following code just before the line that does theconnect:
Winsock1.LocalPort = 0 Winsock1.Connect
Steps to Reproduce Behavior
The following sample demonstrates how to reproduce the issue and how towork around it. In the code "myserver" indicates any Windows 2000 or Windows NT Serverrunning Simple TCP/IP Services, which includes an Echo server on Port 7.
Start a new project in Visual Basic. Form1 is created by default.
Add the Windows Socket Control to Form1.
Add the following code to the form:
Option Explicit Private Sub Form_Load() Dim res As Long Winsock1.LocalPort = 2500 Winsock1.RemoteHost = "myserver" Winsock1.RemotePort = 7 Winsock1.Connect End Sub Private Sub Winsock1_Error(ByVal Number As Integer, _ Description As String, ByVal Scode As Long, _ ByVal Source As String, ByVal HelpFile As String, _ ByVal HelpContext As Long, CancelDisplay As Boolean) MsgBox Description, vbOKOnly, "Winsock Error: " & Number CancelDisplay = True End Sub
Run the program.
Exit the program.
Run the program again. Note that this causes a dialog box to appear with the error message:
Address in use.
To correct the code, change the line:
Winsock1.LocalPort = 2500
Winsock1.LocalPort = 0
and perform steps 4 through 6 several times. You should not get any errors.