Socket Connect/Disconnect

Hello.  I have a specific question I hope someone in the forum can answer.

I am writing an application that will collect data from several instruments over tcp.  I am implementing this by assigning a socket to each instrument I want to connect to, and then establishing a connection to the instruments IP address (port 502, MODBUS communication protocol requires this port).  I have a form where a user can enter the IP address of the instrument and then click a button beside it to test if the application is able to connect to the specified instrument.  The button procedure Connects to the socket and then Shuts it down and closes it.  I have no problems connecting to it initially, but if I try to test the connection more than once I get an exception that reads:

"Only one usage of each socket address (protocol/network address/port) is normally permitted."

I tried setting the ReuseAddress Socket option at the socket level but I still get this error.  Please let me know if there is a way I can avoid this exception and proceed with the connection.  Here is some relevant code, I hope it helps.

public bool Connect()

{

IPAddress LocalIP = IPAddress.Any;

try

{

m_sktAnalyzer = new Socket(AddressFamily.InterNetwork,

SocketType.Stream, ProtocolType.Tcp);

IPEndPoint AnalyzerEndPoint = new IPEndPoint(m_ipInstrumentIP, 502);

IPEndPoint LocalEndPoint = new IPEndPoint(LocalIP, 502);

m_sktAnalyzer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

m_sktAnalyzer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);

m_sktAnalyzer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);

m_sktAnalyzer.Bind(LocalEndPoint);

m_sktAnalyzer.Connect(AnalyzerEndPoint);

}

catch (Exception ex)

{

MessageBox.Show("Exception: " + ex.Message);

return false;

}

return true;

}

public bool Disconnect()

{

try

{

m_sktAnalyzer.Shutdown(SocketShutdown.Both);

m_sktAnalyzer.Close();

return true;

}

catch (Exception ex)

{

return false;

}

}



Answer this question

Socket Connect/Disconnect

  • PrasadC

    You are binding to a SPECIFIC local port.
    This is by design. When you close a connection the connection goes into a TIME_WAIT state.
    You can verify this through netstat -a

    I would imagine that you don;t need to bind to a specific local port. You might need a
    specific remote port, thats fine.

    Take the bind out and let the TCP determine the best local port to use



  • Jacco Mintjes

    Works like a charm. Thanks for the speedy reply.
  • Socket Connect/Disconnect