user626528
user626528

Reputation: 14399

TcpListener - No connection could be made because the target machine actively refused it

        int port = 44344;

        var thread = new Thread(
            () =>
            {
                TcpListener listener = null;
                try
                {
                    listener = new TcpListener(IPAddress.Any, port);
                    listener.Start();

                    while (true)
                    {
                        var client = listener.AcceptTcpClient();
                    }
                }
                catch (ThreadInterruptedException)
                { }

                if (listener != null)
                    listener.Stop();
            });
        thread.Start();

        Thread.Sleep(TimeSpan.FromSeconds(1));

        var socket = new Socket(SocketType.Stream, ProtocolType.IP);
        socket.Connect("localhost", port);

This code fails on the last line with "No connection could be made because the target machine actively refused it" exception, when running on my PC. Any ideas what can be the reason and how to fix it?

Upvotes: 2

Views: 1377

Answers (1)

user626528
user626528

Reputation: 14399

The solution was to create the client socket with an AddressFamily parameter specified:

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

Upvotes: 3

Related Questions