I keep getting a SocketException: Address already in use
when running my program multiple times.
Minimal example:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace test
{
class Program
{
static TcpListener listener;
static void Main(string[] args)
{
listener = new TcpListener(new IPEndPoint(IPAddress.Any, 3349));
listener.Start();
listener.BeginAcceptSocket(Accept, null);
Console.WriteLine("Started!");
// Simulate a random other client connecting, nc localhost 3349 does the same thing
var client = new TcpClient();
client.Connect("localhost", 3349);
Thread.Sleep(2000);
listener.Stop();
Console.WriteLine("Done!");
}
static void Accept(IAsyncResult result)
{
using(var socket = listener.EndAcceptSocket(result))
{
Console.WriteLine("Accepted socket");
Thread.Sleep(500);
socket.Shutdown(SocketShutdown.Both);
}
Console.WriteLine("Socket fully closed");
}
}
}
Run the program twice (dotnet run
): the first time it will complete normally, but the second time it will fail saying "Address already in use".
Note that the missing dispose of client
is not the problem here -- I can replicate the same error manually by using nc localhost 3349
.
How can I clean up the listener so that I don't run into the error?
OS & .NET info:
dotnet --version
2.1.103
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 16.04.4 LTS
Release: 16.04
Codename: xenial
This problem is not present on Windows. It also doesn't occur when using mono
, so this seems to be specific to Microsoft's linux implementation.