Tim
Tim

Reputation: 2911

TcpListener actively refused connection

I am maintaining an application that uses a TcpListener to listen for incoming communication. The following code opens the connection:

Dim listener As TcpListener
_listenFailed = False
Try
    listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)
    listener.Start()
Catch ex As Exception
    ' an error here means the settings are likely bogus
    _listenFailed = True
    Return
End Try

While Not _stoplistening
{
    ' Accept connection
}

The problem that I am having is that when i send a file from a different computer, I get the error "No connection could be made because the target machine actively refused it."

I have checked for firewalls and antivirus, and there were no blocks. I used

netstat -a -n

to determine that the port is active and listening. Both applications are running from Visual Studios in Administrator mode, not that this should make a difference. I have a break point set at the first line of the accept connection code, but it never gets run.

I stopped the application and examined the TcpListener, and found that there were a couple errors if I dug deep down. At TcpListener.LocalEndpoint.IPEndPoint.IPAddress.Address.ErrorCode there was the error 10045, "OperationNotSupported". Also, at TcpListener.Socket.RemoteEndPoint.ErrorCode there was an error 1057, "A request to send or receive data was disallowed because the socket is not connected, and (when sending on a datagram socket using a sendto call) no address was supplied. I don't know if either of these errors are relevant.

If anyone has any insights as to what might be causing this problem, or steps that can be taken to trace the root of the issue, I would be grateful.

Upvotes: 2

Views: 3191

Answers (1)

tcarvin
tcarvin

Reputation: 10855

Try changing this:

listener = New TcpListener(System.Net.IPAddress.Parse(Me.Host), Me.Port)

To this:

listener = New TcpListener(System.Net.IPAddress.Any, Me.Port)

This will allow you to listen across all network interfaces.


Additionally, you can use IPv6Any instead of Any if you want to target IPv6 instead. This choice has an impact on the address used by the client side obviously.

Upvotes: 1

Related Questions