Hello all, I’m doing some further TCP stress testing and I noticed a replicable exception using the Socket.Bind() method.
I’m hosting a TCP server on the local network. When I create the socket and call the bind method the first time, everything seems to work okay. If I manually close the TCP connection (say the ethernet connection closes), and then reopen the server later, the .Bind() method throws an invalid operation exception as shown below:
Code Throws Exception
IPEndPoint ServerEndpoint = new IPEndPoint(EthernetController.IpAddress, tcpPort);
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(ServerEndpoint);
_serverSocket.Listen(int.MaxValue);
Exception Message
#### Exception System.InvalidOperationException - CLR_E_INVALID_OPERATION (6) ####
#### Message:
#### GHIElectronics.TinyCLR.Devices.Network.Provider.NetworkControllerApiWrapper::Bind [IP: 0000] ####
#### System.Net.Sockets.Socket::Bind [IP: 001a] ####
#### Charge_Control.MainApp::EthernetConnectionEstablished [IP: 002a] ####
#### GHI_Framework.EthernetController::NetworkConnectionChanged [IP: 00cb] ####
#### GHIElectronics.TinyCLR.Devices.Network.NetworkController::OnNetworkAddressChanged [IP: 000e] ####
#### GHIElectronics.TinyCLR.Devices.Network.Provider.NetworkControllerApiWrapper::<.ctor>b__8_1 [IP: 001f] ####
Exception thrown: 'System.InvalidOperationException' in GHIElectronics.TinyCLR.Devices.Network.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in GHIElectronics.TinyCLR.Devices.Network.dll
However! If I add a ReuseAddress socket option before calling the .Bind() method, the exception does not trigger:
Code Does Not Throw Exception
IPEndPoint ServerEndpoint = new IPEndPoint(EthernetController.IpAddress, tcpPort);
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_serverSocket.Bind(ServerEndpoint);
_serverSocket.Listen(int.MaxValue);
So, is this the intended way this is supposed to work? And if so, does enabling this ReuseAddress option cause any known issues I should be aware of?
I’m adding a link to a previous post with a similar issue here:
Previous Post