Tcp 10061 connection refused ошибка

  • Question

  • I hosted a wcf service application using windows services. When my client (ASP.NET) tries to call the service class hosted by the windows service, I get this error «TCP error code 10061: No connection could be made because the target machine actively refused it. «. Is there a fix for this? The same code works fine if I host it using a console application.

Answers

  • What port are you listening on? Is that port unblocked in your windows firewall?

All replies

  • What port are you listening on? Is that port unblocked in your windows firewall?

  • Yes, my firewall was blocking it. I got around it and it fixed the problem.

    • Proposed as answer by

      Friday, May 23, 2014 1:28 PM

  • Hi,

    Evn i am gettin the same error. Can u tell me wat is the fix.

  • I am getting the same error — but only when I change my return type to a cutom object. CLR types work fine — i.e. an IList of Strings, but not, say, MyResponseObj. I’m running the asp.net development server on port 1212, with a wsHttpBinding. Like I said, the problem seems to be with the return type which is marked up with the DataContract — DataMember tags, like my other custom objects that work fine as input objects. I am able to pass in an arbitrarily complex object of custom types no problem — but the server tanks with a custom return type.

    Any suggestion would be appreciated. Thanx — Ian

  • Brian

    I’ve configured trace in the web.config file as per the article, but no output or log file is generated. Do I need to create a trace object in my test code (NUnit) to explicitly start the trace segment?

    Or should the web.config entry be sufficient?

    Thanks,

    Ian

  • Kenny,

    I’ve unblocked the port on the firewall and still unable to connect.

    What was the fix?

  • For problem returning custom objects, turns out my IList<T> member variable, since it could be nullable, required this in the data contract: [DataMember(EmitDefaultValue = false)]
    That is what was causing the service to refuse the connection. Now all is well again.  A newbie error no doubt, but I never even heard of WCF before I started at my new company.  =o)

    • Proposed as answer by
      JeffKite
      Wednesday, August 14, 2013 6:32 PM

  • What port are you using? What binding is this? Can you connect to the port using IE (assuming you have an HTTP GET metadata enabled)?

  • Hi ,

    I am getting this error if I host it using a console application. it works fine if client is asp.net. Is there a fix for this?

    -ravi

  • try to remove and add service refrences again…it will help you to connect wcf…

  • Hi JothiMurugan,

    I am also getting same error when I host with the windows service.

    Same application when hosted in Console application, works fine.

    Can you please help me with the fix.

    Thanks in advance.

    Sakthi

  • hi
    i don’t know it will helpfull to u or not but u should try it
    first u click on  host  project and  click on Start new instance
    then u should run windows application

  • I have configured Tracing and I see my trace files just fine, the prblem is I don’t see an Error icon. 

    I’m looking through all the activities in the trace viewer and the one for my service operation has To and from transport messages, I can see the start for the activity but there is nothing indicating an error and I setup it up for  switchValue=»Error,ActivityTracing». 

    ??


    Santiago Perez

  • Hi,
    I am trying to write a WCF service with transport level security and basicHTTP binding. I am using a custom Membership provider to authenticate a client call to the service by authenticating the User ID and password passed to the service. I believe that WCF does not allow UserID/Password auth without having SSL certificate installed because the UserID/password are sent as clear text. I am currently in development and I tried installing the test certificate (X.509) on my dev machine running the service but w/o any success.
    My service web.config looks like this

    <

    system.serviceModel>

    <

    services>

    <

    service behaviorConfiguration=«LCCService.rbagLCWS_ServiceBehavior«

    name=«LCCService.rbagLCWS_Service«>

    <

    endpoint address=«»

    binding=«basicHttpBinding«

    bindingConfiguration=«LCCService.rbagLCWS_ServiceBinding«

    contract=«LCCService.IrbagLCWS_service«>

    </

    endpoint>

    <

    endpoint address=«mex«

    binding=«mexHttpBinding«

    contract=«IMetadataExchange« />

    </

    service>

    </

    services>

    <

    behaviors>

    <

    serviceBehaviors>

    <

    behavior name=«LCCService.rbagLCWS_ServiceBehavior«>

    <

    serviceCredentials>

    <

    userNameAuthentication userNamePasswordValidationMode=«MembershipProvider« membershipProviderName=«PasswordProvider«/>

    </

    serviceCredentials>

    <

    serviceMetadata httpGetEnabled=«true« />

    <

    serviceDebug includeExceptionDetailInFaults=«true« />

    </

    behavior>

    </

    serviceBehaviors>

    </

    behaviors>

    <

    bindings>

    <

    basicHttpBinding>

    <

    binding name=«LCCService.rbagLCWS_ServiceBinding«>

    <

    security mode=«Transport«>

    <

    transport clientCredentialType=«Basic«/>

    </

    security>

    </

    binding>

    </

    basicHttpBinding>

    </

    bindings>

    </

    system.serviceModel>

    When I try to call the service using the client w/o having the test certification installed, I get the following error:
    Could not connect to https://XYZ.com/rrxainet/LCCWCFService/rbagLCWS_service.svc. TCP error code 10061: No connection could be made because the target machine actively refused it XXX.XXX.XX.XXX:443.

    I have spent almost 2 days trying to figure out the solution and how to successfully install the test certificate to get it working but to no avail.

    Please can someone help. I really appreciate it!!!

  • hi guys,

    i am new to dot net. when i am using the folling program for connecting the particuler port it is giving the error.

    int

    timout = Convert.ToInt32(txttimeout.Text);

    int port = 5000;

    IPAddress localAddr = IPAddress.Parse(«127.0.0.1»);

    IPEndPoint remoteEndPoint = new IPEndPoint(localAddr, port);

    TcpClient NetworkClient = TimeOutSocket.Connect(remoteEndPoint, timout);

    NetworkStream networkstream = NetworkClient.GetStream();

    StreamReader streamReader = new StreamReader(networkstream);

    string line = streamReader.ReadToEnd(); //streamReader.ReadLine();

  • I got the same message after adding the registry value  «KeepAliveTime» with value 300000 in the window registry under HKEY_LOCAL_MACHINESystemCurrentControlSetServicesTcpipParameters.

    When I removed the window registry «KeepAliveTime», it resumed normal.

    Is there any settings I have to check ?

  • Hi All,

     I am new to WCF. I have created a WCF Service and hosted it in Windows Service. I have got a below Error when tring to create Client Proxy for the service.

    Error Message:

    «There was an error downloading ‘http://localhost:8051/Service1/’.
    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8051
    Metadata contains a reference that cannot be resolved: ‘http://localhost:8051/Service1/’.
    Could not connect to http://localhost:8051/Service1/. TCP error code 10061: No connection could be made because the target machine actively refused it 127.0.0.1:8051.

    Unable to connect to the remote server
    No connection could be made because the target machine actively refused it 127.0.0.1:8051
    If the service is defined in the current solution, try building the solution and adding the service reference again.»

    I have seen some posts related to Issue like unblocking the port in Firewall. I have unblocked all ports from Firewall, Still the Issue raising while create Client Proxy. Some one can help me on this Problem. I have Pasted my configuration file below.

    <system.serviceModel>
        <services>
          <service name=»WcfService1.Service1″ behaviorConfiguration=»WcfService1.Service1Behavior»>
            <!— Service Endpoints —>
            <endpoint address=»» binding=»wsHttpBinding» contract=»WcfService1.IService1″>
            </endpoint>
            <!—<endpoint address=»» binding=»netTcpBinding» contract=»WcfService1.IService1″></endpoint>—>
            <!—<endpoint address=»mextcp» binding=»mexTcpBinding» contract=»IMetadataExchange»/>—>
            <endpoint address=»mex» binding=»mexHttpBinding» contract=»IMetadataExchange»/>
            <host>
              <baseAddresses>
                <add baseAddress = «http://localhost:8051/Service1/» />
              </baseAddresses>
            </host>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name=»WcfService1.Service1Behavior»>
              <!— To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment —>
              <serviceMetadata httpGetEnabled=»true»/>
              <!— To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information —>
              <serviceDebug includeExceptionDetailInFaults=»false»/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>

    Please reply me to solve this problem.

  • I started getting this problem in VS 2008 IDE when I’m testing my web services.  Not a firewall issue.  Anyone find a positive solution to this??

    My Web Service test web application used to work fine a few months ago — now when I test it I get this error?  So I’m guessing some OS update has broken VS 2008 IDE for web services??

    Rob

  • Solved the problem for my case (appears to a Project’s Web Service reference issue):

    In VS 2008 IDE

    In your actual Web Services Project (with the ASMX source) — My Project | Web | Use Visual Studio Development Server | Auto-assign Port.

    a. If this is hard coded to a specific port you’ll need to verify the calling Project’s Web Service references match the same port and reference.

    b. Open your calling project — My Project | References — remove your Web Service references (Type = Service) — be sure to note the ReferenceName you used.  Now Add Service Reference back again — Discover Services in Solution, select the service
    and be sure to re-enter the same ReferenceName you used originally.

    If your Web Service project is configured differently or you reference external web services, then it might just be a case of removing and re-adding the web service back being sure to use the same ReferenceName so you project references stay intact.

    Rob.

    • Proposed as answer by
      Rob Ainscough
      Monday, August 2, 2010 10:23 PM

  • Hi I'm new to WCF.. I'm trying to invoke free web service
    

    http://www.mindreef.net/svc/hashservice/servicesHashClassSoap?wsdl....

    So i have created a client but it gives me an exception..Please help me

    Could not connect to http://localhost:8050/hashservice/services/HashClassSoap.
    
    
    TCP error code 10061: No connection could be made because the target machine 
    
    
    actively refused it 127.0.0.1:8050. 
    
    Server stack trace: 
     at System.ServiceModel.Channels.HttpOutput.WebRequestHttpOutput.GetOutputStream()
     at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
     at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.
    
    
    HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
     at System.ServiceModel.Channels.RequestChannel.Request(Message message,
    
    
     TimeSpan timeout)
     at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message,
    
    
     TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean 
    
    
    oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan
    
    
     timeout)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action,
    
    
     Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(
    
    
    IMethodCallMessage methodCall, ProxyOperationRuntime operation)
     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    
    Exception rethrown at [0]: 
     at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,
    
    
     IMessage retMsg)
     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData,
    
    
     Int32 type)
     at HashClassSoap.CheckHash(CheckHashRequest request)
     at HashClassSoapClient.HashClassSoap.CheckHash(CheckHashRequest request)
    
    
    
    

  • you have added your wcf reference by selecting wcf project node. to resolve it select your test project node and add wcf reference. i hope it will work.

  • you have added your wcf reference by selecting wcf project node. to resolve it select your test project node and add wcf reference. i hope it will work.

  • Yeah! First time I ever fixed ANYTHING! Error went away when changed properties of project to use IIS instead of local directory.  Set the project to use IIS, click the button to create a virtual directory and…c’est voila!.  Good luck.

  • TrollSpouse, I seem to have this problem, but I don’t understand the solution you found. Could you be more specific where in properties you configured  to use IIS instead of local directory? Thanks.

  • Make sure that «Net.Tcp Listener» is running go to  ControlPanel/Administrative Tools/Services
    also «Net.Tcp Port Sharing»  Service.

    • Proposed as answer by
      M.El-Baz
      Saturday, October 22, 2016 5:57 PM

  • My Net.tcp listener shows as starting, however starts… it shows the net.tcp Port Sharing as started, as well as the Windows Process Activation Service as started… i get the 10061 error as well… any idea how I can fix this?  would a service admin
    logon do it versus Local System/Service?

  • did you find the solution I have the same problem «TCP error code 10061: No connection could be made because the target machine actively refused it.

    when the service and application on the same PC its working fine but when I deployed the client application on another pc, i got the above error.

  • I’m quite interested in this as well, as I’ve got the same issue. I had my WCF service, that uses TCP for the transport protocol, on a Windows 2003 R2 Server. We’re writing a WPF application. It works fine for me, but no other user can run it. So in an
    effort to try and figure out what’s wrong I am now running the WCF service on my machine (a Windows 7 Ultimate machine). I’ve put the WCF service into IIS. I made sure the Windows Firewall allows for the port I want to use (9000). But I started getting these,
    «No connection could be made because the target machine actively refused it» and then it gives my machine’s IP address. I saw back in 2011 that Ivendur suggested making sure that Net.Tcp Listener Adapter and Net.Tcp Port Sharing Service services both be running.
    They weren’t on my machine, but they are now, and that didn’t resolve the issue, I’m still getting that actively refused error message.


    Rod

  • I am receiving the same error when i  try to connect 2 clients to the same server.

    I make myself clear…

    i created a lan chat program that works just fine with 1 server form who listens (I used TPCListener) on 8080, and 1 client form that connects to it

    but if i try to open another client form and connect to the same server form at 8080 i get the error…

    i believed that, since the 2 clients use a different port to connect to localost:8080 the socket should not give an error…

    I don’t know how to solve this!


    +++ Alex +++

  • VMWARE Virtual network can cause such a problem (happened to me) — ‘Restore Defaults’ is the solution!


    Di-ma-N

  • For mine, I had to go into my router settings and use port forwarding.

  • It can be that if your server where AGPM client is started was an AGPM server before, that still these settings are used and therefore point to a wrong server. Just delete all entries of HKEY_LOCAL_MACHINESOFTWAREMicrosoftAgpm and below only enter the
    two following strings:

    DefaultArchive = AGPMServerName.company.com:4600
    InstallDirClient = C:Program FilesMicrosoftAGPMClient

    Note that «AGPMServerName.company.com» is the FQDN-name of the AGPM server. If you have another port than 4600 and/or another installation directory of your client, please adapt it (hust check before you delete anything).

  • I got similar error, I had to reboot the web server.

    Could not connect to net.tcp://testwe01/Services/Jse.EquitySystem.DataService/PricesDataService.svc

    The connection attempt lasted for a time span of 00:00:01.0312568. TCP error code 10061: No connection could be made because the target machine actively refused it xx.xx.xx.xxx:808.

  • I hosted a wcf service application using windows services. When my client (ASP.NET) tries to call the service class hosted by the windows service, I get this error «TCP error code 10061: No connection could be made because the target machine actively
    refused it. «. Is there a fix for this? The same code works fine if I host it using a console application.

    https://hipmusic.co/

    • Edited by
      HezekiahNig
      Thursday, July 25, 2019 11:20 PM

Let us examine the error 10061 connection refused SQL server and the reasons or the causes for the Error and learn some troubleshooting tips from our MSSQL Support services at Bobcares to remove the error in a few simple steps.

Error 10061 while connecting SQL server

10061 connection refused sql server

The server’s error code 10061 indicates Connection Refused. We were unable to establish a connection because the target system actively refused it.

One of the, most common reasons for the error is the misconfigured server, the full server. or an incorrect port specified by the client.

Error

A network or instance-specific error occurred when attempting to connect to the server.


The server could not be found or was unavailable. Ensure the accuracy of the instance name and that SQL Server is set to enable remote connections.

(TCP Provider, error: 0 - No connection could be established since the target computer actively refused it.)
(Error: 10061, Microsoft SQL Server)

This issue occurs because the Windows firewall closes the TCP/IP connection to the SQL server: Allowing SQL Server Access to configure in the Windows Firewall.

1: Fix Microsoft SQL Server Error 10061?

Firstly, We have to Make sure the TCP/IP Protocol is active and up and running. We may access the SQL server and configuration manager by heading to All applications -> Microsoft SQL server -> Configuration Tools.

Choose the client protocols (based on the operating system we are using, 32-bit or 64-bit). Make sure TCP/IP Protocol is active on the right hand.

While the computer displays the “SQL Server Issue 10061 Connection Denied” error message, we can try the following troubleshooting methods:

No connection with TCP error. HTML 10061: The connection could not be scheduled because the destination machine refused to accept it.

We must enable an exception, generally the port, in the Windows firewall application. We can disable the firewall software.

After the shutdown, the software may resume normal operation. If this is the case, there is a strong sign that the error is the cause of a firewall.

So, now that we’ve identified that the problem is with the firewall, we can enable it. Turn on the firewall and make a minor port exception.

Keep in mind that this error can be caused by a variety of factors other than the Firewall.

Error code 10061: Unable to connect to TCP: The target has obviously rejected the machine, thus we are unable to connect.

One of the alternatives is to configure an exception for the port in the new firewall window. The exact program might work properly after disabling it.

This might point out the fact that the firewall was indeed the main cause for triggering the error. So in this case we have to quickly enable the firewall and put the port as an exception.

2: Fix error 10061 connection refused?

Here are some troubleshooting actions we can do to avoid or resolve the 10061 connection rejected SQL server error.

Examine the Enterprise Console configuration. From the Windows Start menu, launch some PRTG Enterprise Console programs. Step Examine the PRTG administrative tool’s settings. Compare the settings. After that, put the adjustments into action.

TCP error number 10061: Unable to bind Because the specified target computer actively refused to connect, the connection could not be created.

Check to see if TCP/IP is enabled. Navigate to All Programs -> Microsoft SQL Server 2008 -> Configuration Tools -> SQL Server Configuration Manager and launch it.

Select Client Networks from the menu on the left (depending on the 32- or 64-bit operating program). Check the right side to see if TCP/IP is enabled.f.

[Need assistance with similar queries? We are here to help]

Conclusion

To conclude we have learned more about the error 10061 connection refused SQL server and the specific triggers that causes the error to occur. With the support of our MSSQL support services, we have learned all of the possible triggers and effective solutions to deal with the error in a few simple steps and quickly.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Comment *

Name *

Email *


error 10061 откуда берется при connect

От:

maxidroms

Россия

 
Дата:  05.09.05 10:10
Оценка:

При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?
Этот коннект хоть пробивается до серверного приложения или он не проходит сам компьютер даже, на котором это серв. приложение стоит?

Помогите плз!!! Клиенты недовольны. т.к. соединиться нельзя вообще никак! Это сообщения не переодически появляется а ПОСТОЯННО, но славо богу не у всех =(


Re: error 10061 откуда берется при connect

От:

TarasCo

 
Дата:  05.09.05 10:23
Оценка:

Здравствуйте, maxidroms, Вы писали:

M>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?

M>Этот коннект хоть пробивается до серверного приложения или он не проходит сам компьютер даже, на котором это серв. приложение стоит?

Где угодно
1)На локальной машине. Тогда «виноват» скорее всего персональный фаерволл
2)На шлюзе/прокси и.т.п. «Виноват» скорее всего межсетевой экран ( настоящий фаервол )
3)На серевре — скоре всего, опять же фаерволл.

В нормальной ситуации эта ошибка возникает, если на сервере не прослушивается запрашиваемый порт. В этом случае он отвечает RST+FIN что и означает активный отказ от соединения. Поскольку это происходит не со всеми клиентами, то стоит предположить, что порт указан верно, следовательно соединения отвергаются не сервером ( нужно проверить настройки клиентского ПО, если там задается порт ). Кроме серевра соединения могут отвергнуть фаерволл, прокси и.т.п. Если сервер расположен в инетнете, первым делом нужно проверить настройки прокси для выхода в интернет для этих пользователей.

Да пребудет с тобою сила


Re[2]: error 10061 откуда берется при connect

От:

maxidroms

Россия

 
Дата:  05.09.05 10:30
Оценка:

Здравствуйте, TarasCo, Вы писали:

TC>Здравствуйте, maxidroms, Вы писали:


M>>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?

M>>Этот коннект хоть пробивается до серверного приложения или он не проходит сам компьютер даже, на котором это серв. приложение стоит?

TC>Где угодно

TC>1)На локальной машине. Тогда «виноват» скорее всего персональный фаерволл
TC>2)На шлюзе/прокси и.т.п. «Виноват» скорее всего межсетевой экран ( настоящий фаервол )
TC>3)На серевре — скоре всего, опять же фаерволл.

TC>В нормальной ситуации эта ошибка возникает, если на сервере не прослушивается запрашиваемый порт. В этом случае он отвечает RST+FIN что и означает активный отказ от соединения. Поскольку это происходит не со всеми клиентами, то стоит предположить, что порт указан верно, следовательно соединения отвергаются не сервером ( нужно проверить настройки клиентского ПО, если там задается порт ). Кроме серевра соединения могут отвергнуть фаерволл, прокси и.т.п. Если сервер расположен в инетнете, первым делом нужно проверить настройки прокси для выхода в интернет для этих пользователей.

А что может быть с настройками не то если:
Стоит обычная пользовательская машина, выход по модему через провайдера. Все после этого встречается мой сервак т .к. он висит на выделенном ай-пи. в интернете.

Коннекты с разных городов. Это может значить то что у провайдера закрыт порт или еще что то? Иными словами дело в провайдере? Ведь при модемном соединении никаких предварительных настроек Рабочей группы и ай-пи адреса не делается?!


Re[3]: error 10061 откуда берется при connect

От:

TarasCo

 
Дата:  05.09.05 11:07
Оценка:

Здравствуйте, maxidroms, Вы писали:

M>Здравствуйте, TarasCo, Вы писали:


TC>>Здравствуйте, maxidroms, Вы писали:


M>>>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?

M>>>Этот коннект хоть пробивается до серверного приложения или он не проходит сам компьютер даже, на котором это серв. приложение стоит?

TC>>Где угодно

TC>>1)На локальной машине. Тогда «виноват» скорее всего персональный фаерволл
TC>>2)На шлюзе/прокси и.т.п. «Виноват» скорее всего межсетевой экран ( настоящий фаервол )
TC>>3)На серевре — скоре всего, опять же фаерволл.

TC>>В нормальной ситуации эта ошибка возникает, если на сервере не прослушивается запрашиваемый порт. В этом случае он отвечает RST+FIN что и означает активный отказ от соединения. Поскольку это происходит не со всеми клиентами, то стоит предположить, что порт указан верно, следовательно соединения отвергаются не сервером ( нужно проверить настройки клиентского ПО, если там задается порт ). Кроме серевра соединения могут отвергнуть фаерволл, прокси и.т.п. Если сервер расположен в инетнете, первым делом нужно проверить настройки прокси для выхода в интернет для этих пользователей.

M>А что может быть с настройками не то если:


M>Стоит обычная пользовательская машина, выход по модему через провайдера. Все после этого встречается мой сервак т .к. он висит на выделенном ай-пи. в интернете.

M>Коннекты с разных городов. Это может значить то что у провайдера закрыт порт или еще что то? Иными словами дело в провайдере? Ведь при модемном соединении никаких предварительных настроек Рабочей группы и ай-пи адреса не делается?!

1)
Возможны «происки» встроенных фаерволов. Например стандартному фаерволу из Win XP SP2 может не понравится идея соедиится с портом N на адрес M. IMHO любой персональный фаервол будет блокировать такие попытки.

2)Дело в провайдере?
про провайдеров не знаю, какая у них там политика безопасности? Но я бы на их месте тоже все подряд порты не открывал. В любом случае, можно обратиться в саппорт и поинтересоваться.

Да пребудет с тобою сила


Re[4]: error 10061 откуда берется при connect

От:

maxidroms

Россия

 
Дата:  05.09.05 11:09
Оценка:

Здравствуйте, TarasCo, Вы писали:

TC>Здравствуйте, maxidroms, Вы писали:


M>>Здравствуйте, TarasCo, Вы писали:


TC>>>Здравствуйте, maxidroms, Вы писали:


M>>>>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?

M>>>>Этот коннект хоть пробивается до серверного приложения или он не проходит сам компьютер даже, на котором это серв. приложение стоит?

TC>>>Где угодно

TC>>>1)На локальной машине. Тогда «виноват» скорее всего персональный фаерволл
TC>>>2)На шлюзе/прокси и.т.п. «Виноват» скорее всего межсетевой экран ( настоящий фаервол )
TC>>>3)На серевре — скоре всего, опять же фаерволл.

TC>>>В нормальной ситуации эта ошибка возникает, если на сервере не прослушивается запрашиваемый порт. В этом случае он отвечает RST+FIN что и означает активный отказ от соединения. Поскольку это происходит не со всеми клиентами, то стоит предположить, что порт указан верно, следовательно соединения отвергаются не сервером ( нужно проверить настройки клиентского ПО, если там задается порт ). Кроме серевра соединения могут отвергнуть фаерволл, прокси и.т.п. Если сервер расположен в инетнете, первым делом нужно проверить настройки прокси для выхода в интернет для этих пользователей.

M>>А что может быть с настройками не то если:


M>>Стоит обычная пользовательская машина, выход по модему через провайдера. Все после этого встречается мой сервак т .к. он висит на выделенном ай-пи. в интернете.

M>>Коннекты с разных городов. Это может значить то что у провайдера закрыт порт или еще что то? Иными словами дело в провайдере? Ведь при модемном соединении никаких предварительных настроек Рабочей группы и ай-пи адреса не делается?!


TC>1)

TC>Возможны «происки» встроенных фаерволов. Например стандартному фаерволу из Win XP SP2 может не понравится идея соедиится с портом N на адрес M. IMHO любой персональный фаервол будет блокировать такие попытки.

TC>2)Дело в провайдере?

TC>про провайдеров не знаю, какая у них там политика безопасности? Но я бы на их месте тоже все подряд порты не открывал. В любом случае, можно обратиться в саппорт и поинтересоваться.

Ну хоть вы меня успокоили что это не в клиентской и не в серверной части дело…а то меня уже на куски тут готовы разорвать


Re[2]: error 10061 откуда берется при connect

От:

MaximE

Великобритания

 
Дата:  06.09.05 09:45
Оценка:

10 (1)

TarasCo wrote:

[]

> В нормальной ситуации эта ошибка возникает, если на сервере не прослушивается запрашиваемый порт. В этом случае он отвечает RST+FIN что и означает активный отказ от соединения.

В этом случае отсылается только RST.

[root@localhost max]# tcpdump -i lo tcp port 10000
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet), capture size 96 bytes
13:23:50.494285 IP localhost.localdomain.41915 > localhost.localdomain.10000: S 176260357:176260357(0) win 32767 <mss 16396,sackOK,timestamp 4126888 0,nop,wscale 2>
13:23:50.558286 IP localhost.localdomain.10000 > localhost.localdomain.41915: R 0:0(0) ack 176260358 win 0

2 packets captured
4 packets received by filter
0 packets dropped by kernel


Maxim Yegorushkin

Posted via RSDN NNTP Server 1.9


Re[3]: error 10061 откуда берется при connect

От:

TarasCo

 
Дата:  06.09.05 12:21
Оценка:

Здравствуйте, MaximE, Вы писали:

ME>В этом случае отсылается только RST.

Да, это меня переглючило, мысль ушла . RST+ACK S:0 A:xxxxxxx обычно отвечают
Спасибо за коррективу

Да пребудет с тобою сила


Re: error 10061 откуда берется при connect

От:

Michael Chelnokov

Украина

 
Дата:  10.09.05 11:46
Оценка:

Здравствуйте, maxidroms, Вы писали:

M>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?

Вы рано успокоились насчет серверной части
Почему-то никто не обратил внимания на то что ошибка 10061 — это WSAECONNREFUSED:
Connection refused.
No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

Возможные причины? Реализация сервера. Например он однопоточный, с последовательной обработкой запросов. И пока он обрабатывает один запрос, успевает поступить больше чем backlog (см. второй параметр функции listen) запросов. Все остальные получат WSAECONNREFUSED.
В более сложном случае при большой нагрузке может не успевать доходить ход до потока, делающего accept. С тем же результатом. Посмотрите

здесь

Автор: Michael Chelnokov
Дата: 09.11.01

и что мне тогда посоветовали.


Re[2]: error 10061 откуда берется при connect

От:

MaximE

Великобритания

 
Дата:  10.09.05 12:16
Оценка:

Здравствуйте, Michael Chelnokov, Вы писали:

MC>Здравствуйте, maxidroms, Вы писали:


M>>При коннекте на некоторых машина постоянно возникает 10061. В чем может быть причина?


MC>Вы рано успокоились насчет серверной части

MC>Почему-то никто не обратил внимания на то что ошибка 10061 — это WSAECONNREFUSED:
MC>Connection refused.
MC>No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

MC>Возможные причины? Реализация сервера. Например он однопоточный, с последовательной обработкой запросов. И пока он обрабатывает один запрос, успевает поступить больше чем backlog (см. второй параметр функции listen) запросов. Все остальные получат WSAECONNREFUSED.

В этом случае клиенты получат WSAETIMEDOUT, а не WSAECONNREFUSED.

Когда очередь установленных соединений заполнена, новые клиенты не получают RST на свой SYN (что вызвало бы WSAECONNREFUSED). Новые клиенты не получают ничего на свой FIN, поэтому TCP стэк клиента будет еще несколько раз пытаться установить соединение посылая серверу SYN, пока не соединится успешно или не отвалится по таймауту с ошибкой WSAETIMEDOUT.


Re[3]: error 10061 откуда берется при connect

От:

Michael Chelnokov

Украина

 
Дата:  10.09.05 13:01
Оценка:

Здравствуйте, MaximE, Вы писали:

MC>>Возможные причины? Реализация сервера. Например он однопоточный, с последовательной обработкой запросов. И пока он обрабатывает один запрос, успевает поступить больше чем backlog (см. второй параметр функции listen) запросов. Все остальные получат WSAECONNREFUSED.


ME>В этом случае клиенты получат WSAETIMEDOUT, а не WSAECONNREFUSED.

Максим, я бы не писал если бы не знал. Если проверишь, то увидишь в этом случае именно WSAECONNREFUSED для тех клиентов что не поместились в очередь. WSAETIMEDOUT они получат если совсем ничего не будет в ответ. А в данном случае ответ четкий — сервер активно не захотел принимать входящее соединение.


Re[4]: error 10061 откуда берется при connect

От:

MaximE

Великобритания

 
Дата:  10.09.05 13:07
Оценка:

Здравствуйте, Michael Chelnokov, Вы писали:

MC>Здравствуйте, MaximE, Вы писали:


MC>>>Возможные причины? Реализация сервера. Например он однопоточный, с последовательной обработкой запросов. И пока он обрабатывает один запрос, успевает поступить больше чем backlog (см. второй параметр функции listen) запросов. Все остальные получат WSAECONNREFUSED.


ME>>В этом случае клиенты получат WSAETIMEDOUT, а не WSAECONNREFUSED.


MC> … А в данном случае ответ четкий — сервер активно не захотел принимать входящее соединение.

И что в этом случае сервер отсылает клиенту?


Re[3]: error 10061 откуда берется при connect

От:

Michael Chelnokov

Украина

 
Дата:  10.09.05 13:10
Оценка:

1 (1)

Здравствуйте, MaximE, Вы писали:

ME>Когда очередь установленных соединений заполнена, новые клиенты не получают RST на свой SYN

Не факт. Судя по Стивенсу, POSIX разрешает как игнорировать SYN, так и отвечать на него RST.
В Windows — второй вариант. В BSD — первый.
Давайте будем отталкиваться от того факта что клиенты все же получают RST, т.к. ошибка именно ECONNREFUSED, а не ETIMEDOUT. Т.е. кто-то все же отсылает оный RST. Почему бы не предположить что этот кто-то и есть сервер? Сервер под Windows


Re[5]: error 10061 откуда берется при connect

От:

Michael Chelnokov

Украина

 
Дата:  10.09.05 13:11
Оценка:

Здравствуйте, MaximE, Вы писали:

MC>> … А в данном случае ответ четкий — сервер активно не захотел принимать входящее соединение.


ME>И что в этом случае сервер отсылает клиенту?

RST

Подождите ...

Wait...

  • Переместить
  • Удалить
  • Выделить ветку

Пока на собственное сообщение не было ответов, его можно удалить.

I have a problem with these client and server codes, I keep getting the [Errno 10061] No connection could be made because the target machine actively refused it

I’m running the server on a virtual machine with Windows XP SP3 and the client on Windows 7 64bit, my python version is 2.7.3. What I want to know is how should I edit the code to use the client and server on different networks! Thanks!

server :

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = '0.0.0.0' # Get local machine name
port = 12345                # Reserve a port for your service.


print 'Server started!'
print 'Waiting for clients...'

s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.
c, addr = s.accept()     # Establish connection with client.
print 'Got connection from', addr
while True:
  msg = c.recv(1024)
  print addr, ' >> ', msg
  msg = raw_input('SERVER >> ')
  c.send(msg);
  #c.close()                # Close the connection

client :

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

print 'Connecting to ', host, port
s.connect((host, port))

while True:
  msg = raw_input('CLIENT >> ')
  s.send(msg)
  msg = s.recv(1024)
  print 'SERVER >> ', msg
#s.close                     # Close the socket when done

PS : code is from internet.

After all the hassle with ADFS and the WAP servers that had been on too long. I got this error message on top after a restart of the ADFS server.

“TCP error code 10061: No connection could be made because the target machine actively refused it”

This error message also took a while before I had found it out.

I encountered this error message because I used a PowerShell cmdlet for ADFS. This does not mean that this cannot solve the problem at other times.

No idea if it only occurs on Windows Servers, but my solution is for a Windows Device only.


Lets fix “The connection attempt lasted for a time span“.

The message comes up because your firewall is blocking something. As you can see in the error message: “net.tcp://localhost:1500/policy”. Your connection tries to go over port 1500, but the server blocks this on purpose: “No connection could be made because the target machine actively refused it”.

In my situation I turned off the firewall to see if this was my issue. In a production environment you can do that as well temporarily, but make sure to turn it on again.

To turn off the Windows Firewall with PowerShell use this cmdlet:

Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False

To turn off the Windows Firewall temporarily in the GUI:

  1. Go to start and search for Control Panel.
  2. Search for Firewall.
  3. Open Turn Windows Defender Firewall on or off in the left menu.
  4. Select Turn off Windows Defender Firewall (not recommended).
TCP error code 10061: No connection could be made because the target machine actively refused it
TCP error code 10061: No connection could be made because the target machine actively refused it.

Try to make a connection again.


Summary

Do you have a different solution, or do you have feedback, or other ideas? Let me know in the comments.


A little extra

This post contains PowerShell. Would you like to learn the basics better? I have created a new website to learn basic PowerShell in an ’emulator’ environment.
Click here to go learn Basic PowerShell.


The complete error message

should someone Googling on another part of the error message:

"get-adfsendpoint : Could not connect to net.tcp://localhost:1500/policy. The connection attempt lasted for a time span

of 00:00:02.0781669. TCP error code 10061: No connection could be made because the target machine actively refused it

[::1]:1500.

At line:1 char:1

+ get-adfsendpoint

+ ~~~~~~~~~~~~~~~~

+ CategoryInfo          : OpenError: (:) [Get-AdfsEndpoint], EndpointNotFoundException

+ FullyQualifiedErrorId : Could not connect to net.tcp://localhost:1500/policy. The connection attempt lasted for

a time span of 00:00:02.0781669. TCP error code 10061: No connection could be made because the target machine acti

vely refused it [::1]:1500. ,Microsoft.IdentityServer.Management.Commands.GetEndpointCommand"

Published by

Bas Wijdenes

My name is Bas Wijdenes and I work as a PowerShell DevOps Engineer. In my spare time I write about interesting stuff that I encounter during my work.
View all posts by Bas Wijdenes

Понравилась статья? Поделить с друзьями:
  • Tco prufen ошибка ман тга
  • Taskhost exe что это ошибка
  • Tco handling ошибка ивеко стралис
  • Task scheduler консоль управления mmc обнаружила ошибку оснастки
  • Targem crash reporter crossout ошибка как исправить