Seth
Seth

Reputation: 199

Close The Socket?

I have an application that needs to stream data up to a server over a particular port. When the application starts it performs a number of checks, for network connectivity, a reachable host, among others. I'd like it to also check the port to ensure it's able to receive data.

I have this code:

Private Function CheckPort(ByVal Host As String) As Boolean

  Dim IPs() As IPAddress = Dns.GetHostAddresses(Host)
  Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

  s.Connect(IPs(0), <port # removed>)

  If s.Poll(-1, SelectMode.SelectWrite) Then
    Return True
  End If

  Return False

End Function

The code works well, but I'm concerned that by performing the check I might be inadvertently preventing subsequent messages from the application from reaching the port. Will performing this check interfere with the actual data I want to send to the host? Should I close the socket with s.close() before returning the function?

Upvotes: 1

Views: 1079

Answers (2)

rodolk
rodolk

Reputation: 5907

I mainly agree with CodeCaster's response. If you say the server is buggy, it is also probable that a few minutes after you check the port connection, the connection is broken or even closed by the server. If you still want to do it as a means to reduce risk of making the user write some message that later cannot be sent, this would be a good approach to follow. An alternative is that you can save the data as draft locally or somewhere else for sending it later when the server is available.

Now, going to your code: You are opening a connection inside function CheckPort so when the function finishes you will lose any reference to s, the open socket. In C, you would have a leak of resources; in Java, a garbage collector will take care of the Socket and close it. I don't know how it is in VB but I'd close that socket before leaving the function. In any case it's a healthy practice.

Additionally, when you have data ready to send you won't be able to do it on the same connection if you lose the reference (s) to the open socket or you close the socket (unless VB has any trick that I don't know). You will have to open a new connection to send data. Don't worry, you will be able to do it even if you made the check before. The server will see it as just a different connection, maybe from a different source port (or could be the same if you closed the connection before, that depends on the OS).

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151588

Checking a port before connecting to it is as useful as verifying file existence before opening it: not at all.

The file can be deleted in between checking and opening, and your socket can be closed for a variety of reasons.

Just connect and write to it, it'll throw an appropriate exception when it won't work.

Upvotes: 1

Related Questions