90

I'm using the WCF4.0 template -REST. I'm trying to make a method that uploads a file using a stream.

The problem always occur at

Stream serverStream = request.GetRequestStream();

Class for streaming:

namespace LogicClass
{
    public class StreamClass : IStreamClass
    {
        public bool UploadFile(string filename, Stream fileStream)
        {
            try
            {
                FileStream fileToupload = new FileStream(filename, FileMode.Create);
                byte[] bytearray = new byte[10000];
                int bytesRead, totalBytesRead = 0;
                do
                {
                    bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
                    totalBytesRead += bytesRead;
                } while (bytesRead > 0);

                fileToupload.Write(bytearray, 0, bytearray.Length);
                fileToupload.Close();
                fileToupload.Dispose();
            }
            catch (Exception ex) { throw new Exception(ex.Message); }
            return true;
        }
    }
}

REST project:

[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
    LogicClass.FileComponent rest = new LogicClass.FileComponent();
    return rest.AddStream(filename, fileStream);
}

Windows Form project: for testing

private void button24_Click(object sender, EventArgs e)
{
    byte[] fileStream;
    using (FileStream fs = new FileStream("E:\\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        fileStream = new byte[fs.Length];
        fs.Read(fileStream, 0, (int)fs.Length);
        fs.Close();
        fs.Dispose();
    }

    string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
    request.Method = "POST";
    request.ContentType = "text/plain";
    Stream serverStream = request.GetRequestStream();
    serverStream.Write(fileStream, 0, fileStream.Length);
    serverStream.Close();
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        int statusCode = (int)response.StatusCode;
        StreamReader reader = new StreamReader(response.GetResponseStream());
    }
}

I've turned off the firewall and my Internet connection, but the error still exists. Is there a better way of testing the uploading method?

Stack trace:

at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)

Masoud
  • 8,020
  • 12
  • 62
  • 123
fiberOptics
  • 6,955
  • 25
  • 70
  • 105
  • 2
    You shouldn't need to worry about firewalls or internet connection for local connections. In your code you are connecting to port `8000` but in your error message the port is `3446`. Is this relevant? – Matt Mitchell Mar 14 '12 at 02:45
  • @Graphain that was a typo error. Thanks for mentioning it. Please see my edit. – fiberOptics Mar 14 '12 at 02:49

20 Answers20

155

"Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. It is therefore not a problem in your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port. This may be because it is not running at all or because it is listening on a different port.

Once you start the process hosting your service, try netstat -anb (requires admin privileges) to verify that it is running and listening on the expected port.

update: On Linux you may need to do netstat -anp instead.

Yaur
  • 7,333
  • 1
  • 25
  • 36
  • 4
    thanks for the `netstat -anb` , I don't find the port in the list. Do you know some possible steps to solve this? I have turned off the firewall, disable the anti virus and disable the internet connection, but still error exist. – fiberOptics Mar 14 '12 at 03:44
  • 1
    How are you hosting the service? If you are just hitting f5 out of visual studio it is IIRC hosted in iisexpress.exe. You can look at that same list for the hosting process to figure out what port it is listening on. – Yaur Mar 14 '12 at 03:55
  • 3
    "How are you hosting the service?" This really stopped me to think for a while. I try to run my rest project that host the service to 3445 and run also the windows form project and target the host to 3445 also. Then everything goes fine. Thanks! and Thanks all. You helped me a lot. – fiberOptics Mar 14 '12 at 04:16
  • 1
    I have done all setting (fire wall , port , enable WcF service )on my staging server as told by you but still i am getting same error can you please guide me on this ?? – Trilok Pathak Jan 08 '16 at 05:51
  • if i guess i am listening to wrong port how to correct it on the server how can i make hosted service listen on the port which i have set from web.config file ? i have to go in IIS-> edit binding and add port or from the firewall i need to add port on the server ?? – Trilok Pathak Jan 08 '16 at 07:54
  • netstat: invalid option -- 'b': The correct command is ~$netstat -an b (with a space) – subdavis Jun 14 '16 at 13:23
  • 1
    @suBDavis `-an b` is Linux specific. The original version works just fine (and your updated version does not) on Windows, which is the platform most people are using to develop WCF services. That said, I have updated the answer with the Linux equivalent since this is now the top hit on google for things that are only tangentially related to the original question. – Yaur Jun 15 '16 at 20:32
  • This may seem off topic but this this type of error can happen with Visual Studio too (IIS Express). Close your project and make sure that IIS Express icon in the task manager is deactivated (no longer visible) and try again. – apereira Feb 21 '17 at 16:10
  • If you know the particular port that you need to check status on, you can use the following in windows: netstat -na | find "3446". Note "3446" is the port # from this question - substitute with your own port # as needed. – James Lee Apr 29 '19 at 21:35
  • I was trying to scan images using clamav scanner without installing it in the server and just calling the scanning method through dll and got the error.Seems like i need to install clamav and then need to pass images for scanning. – Bijay Nandagiri Apr 06 '20 at 13:26
  • @JamesLee I was trying to access an API on HTTPS, so I used 443 and it literally just spat back out a blank command prompt line back at me. It appeared to do nothing but ignore it. – vapcguy Sep 21 '20 at 18:01
18

You don't have to restart the PC. Restart IIS instead.

Run -> 'cmd'(as admin) and type "iisreset"

gradosevic
  • 4,809
  • 2
  • 36
  • 51
  • 1
    I see the port when I do `netstat -anb` and also I restarted the server. Still same error, any help? – Tahir Yasin Aug 20 '14 at 13:38
  • 2
    Ah fantastic! restarting `iis` solved this issue for me. non of the other solutions worked This one is underrated! – Jay Oct 26 '16 at 10:58
3

You must set up your system proxy You have to go through this path controlpanel>>internet option>>connnection>>LAN settings>> proxy no tik:use proxy server

2

I got a similar error message like TCP error code 10061: No connection could be made because the target machine actively refused it in my current project. I find this 10061 error code cannot distinguish the case that the service endpoint is not started and the case that it is blocked by the firewall. Often, the firewall can be switched off, but the problem is still there.

You can test your code in the below two ways.

  1. Insert code to get time A that service is started and time B that client sends the request to the server. If B is earlier than A, it can cause this problem.
  2. Change your server port to another port that is also available in the system. You will find the same error code reported.

Above is my fix. It works on my machine. I hope it helps!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cary
  • 372
  • 1
  • 5
  • 14
  • Can you please have a look here? https://stackoverflow.com/questions/52386437/how-to-solve-error-connecting-to-smtp-host-errno-10061-no-connection-could-b – Deva Sep 20 '18 at 12:44
1

I had a similar issue. In my case the service would work fine on the developer machine but fail when on a QA machine. It turned out that on the QA machine the application wasn't being run as an administrator and didn't have permission to register the endpoint:

HTTP could not register URL http://+:12345/Foo.svc/]. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

Refer here for how to get it working without being an admin user: https://stackoverflow.com/a/885765/38258

Community
  • 1
  • 1
Nick Gotch
  • 9,167
  • 14
  • 70
  • 97
1

Check whether the port number in file Web.config of your webpage is the same as the one that is hosted on IIS.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sarath Subramanian
  • 20,027
  • 11
  • 82
  • 86
1

I had the same problem on my web server "No connection could be made because the target machine actively refused it 161.x.x.235:5672". I asked the Admin to open the port 5672 on the web server, then it worked fine.

Hung Vu
  • 5,624
  • 2
  • 30
  • 27
  • 1
    In your server, open Windows Firewall with Advanced Security. Add new inbound/outbound TCP rule, enter port 5672. You'd better ask network administrator to do it for you. – Hung Vu Feb 05 '17 at 22:49
  • Is there a way to know which port is open for SMTP? – singhswat Nov 26 '21 at 14:52
1

I had a similar problem rejecting localhost and 127.0.0.1. cmd(admin) netstat -anb found the port running on 169.254.80.80 (dont know were that ip came from because my network ip was 10.0.0.5. after putting in this IP it worked. This Gives correct IP:

IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress.ToString());
slfan
  • 8,950
  • 115
  • 65
  • 78
1

I also faced problem in .Net Remoting Service in C#.

I got it solved in 3 steps:

  1. Change Port of Protocol in all the files whereever it is being used.
  2. Run your Host Server Program and make it active.
  3. Now run your client program.
jwpfox
  • 5,124
  • 11
  • 45
  • 42
1

I could not restart IIexpress. This is the solution that worked for me

  1. Cleaned the build
  2. Rebuild
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
1

Check if any other program is using that port.

If an instance of the same program is still active, kill that process.

1

If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 25,943
  • 66
  • 198
  • 303
0

With this error I was able to trace it, thanks to @Yaur, you need to basically check the service (WCF) if it's running and also check the outbound and inbound TCP properties on your advance firewall settings.

PinoyDev
  • 949
  • 1
  • 10
  • 21
0

With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.

Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

Resolution: Set the proxy in Web config.

<system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
    </defaultProxy>
</system.net>
SFK
  • 1
  • 2
0

I had a similar issue. In my case VPN proxy app such as Psiphon ، changed the proxy setup in windows so follow this :

in Windows 10, search change proxy settings and turn of use proxy server in the manual proxy

Ali Besharati
  • 918
  • 12
  • 25
0

Make Sure all services used by your application are on, which are using host and port to utilize them . For e.g, as in my case, This error can come, If your application is utilizing a Redis server and it is not being able to connect to it on given port and host, thus producing this error .

Farhan
  • 61
  • 8
0

For my case, I had an Angular SLA project template with ASP.NET Core.

I was trying to run the IIS Express from the Visual Studio WebUI solution, triggering the "Actively refused it" error.

enter image description here


The problem, in this case, wasn't connected with the Firewall blocking the connection.

It turned out that I had to run the Angular server independently of the Kestrel run because the Server was expecting the UI to run on a specific port but wasn't actually.


For more information, check the official Microsoft documentation.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
0

I had similar problem. In launchSettings, my IIS Express was configured on one port, and there was another launch profile that started on another ApplicationUrl with another port.

Starting the web app up with the IIS Express profile led me to have the error.

GeorgiG
  • 1,018
  • 1
  • 13
  • 29
0

I am using the Apache ActiveMQ Artemis AMQP message broker. I started getting the "No connection could be made because the target machine actively refused it" exception when trying to send and receive messages with the broker after a reboot. On a computer where the same type of broker still worked, netstat -anb showed that the broker was listening on the expected port 5672. On the computer with the error, the broker was not listening. On the computer with the error, starting the broker resulted in the following warning's appearing in Microsoft Event Viewer's "Windows Logs > System":

 The system failed to register host (A or AAAA) resource records for network adapter
 with settings:

            Adapter Name : {286EE2DA-3D81-41AE-VE5G-5D761FD3925E}
            Host Name : mypc
            Primary Domain Suffix : myco.com
            DNS server list :
                55.77.168.1, 74.86.130.1
            Sent update to server : 186.952.335.157:45
            IP Address(es) :
              182.269.1.437

 Either the DNS server does not support the DNS dynamic update protocol or the authoritative zone for the specified DNS domain name does not accept dynamic updates.

 To register the DNS host (A or AAAA) resource records using the specific DNS domain name and IP addresses for this adapter, contact your DNS server or network systems administrator.

I was able to use the broker without error after I ran the following in a cmd.exe with administrative privileges, rebooted, and waited about fifteen minutes:

       ipconfig /flushdns
       ipconfig /renew
       ipconfig /registerdns
dabark
  • 33
  • 5
0

You are browsing to 127.0.0.1, which is localhost, or the local machine. When doing this in Windows results in a 401, it may be worth investigating the loopback check registry setting.

Disclaimer: Editing the registry is potentially dangerous if you don't know what you're doing.

First, browse to this key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

Under Lsa, add a new DWORD value called DisableLoopbackCheck, with a value of 1. Then try your request again. If that works, you've found a workaround/solution. However, this setting should not be used in production because it's a security risk. A somewhat better solution would be to revert that change and go to this key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0

Under MSV1_0, create a new Multi-String value called BackConnectionHostNames, with a value that includes the application host name(s) that you want to exclude from the loopback check. Example:

enter image description here

This is recommended over DisableLoopbackCheck because we can disable the check for only the host(s) we need, so it should be more secure, in theory. However, it still leaves the system vulnerable for the specified host names, so only proceed with this solution if the level of risk is acceptable in your situation.

More info here and here.

Tawab Wakil
  • 1,737
  • 18
  • 33