I'm having this strange error, CURL ERROR: Recv failure: Connection reset by peer

This is how it happens, if I did not connect to tướng the server and all of a sudden trying to tướng connect to tướng the server via CURL in PHP I get the error. When I lập cập the CURL script again the error disappears and then works well the whole time, if I leave the remote server idle for about 30mins or reboot the remote server and try to tướng connect again, I get the error again. So it seems lượt thích the connection is idle and then all of sudden the server wakes up and then works and then sleeps again.

This is how my CURL script looks:

$url = Yii::app()->params['pdfUrl'];
$body = 'title='.urlencode($title).'&client_url='.Yii::app()->params['pdfClientURL'].'&client_id='.Yii::app()->params['pdfClientID'].'&content='.urlencode(htmlentities($content));

$c = curl_init ($url);
$body = array(
    "client_url"=>Yii::app()->params['pdfClientURL'],
    "client_id"=>Yii::app()->params['pdfClientID'],
    "title"=>urlencode($title),
    "content"=>urlencode($content)
);
foreach($body as $key=>$value) { $body_str .= $key.'='.$value.'&'; }
rtrim($body_str,'&');

curl_setopt ($c, CURLOPT_POST, true);
curl_setopt ($c, CURLOPT_POSTFIELDS, $body_str);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT  , 20);

$pdf = curl_exec ($c);
$errorCode = curl_getinfo($c, CURLINFO_HTTP_CODE);
$curlInfo = curl_getinfo($c);
$curlError = curl_error($c);

curl_close ($c);

I'm totally out of ideas and solutions, please help, I'll appreciate it!!!

If I verbose the output to tướng see what happens using

curl_setopt ($c, CURLOPT_VERBOSE, TRUE);
curl_setopt($c, CURLOPT_STDERR, $fp); 

I get the following

* About to tướng connect() to tướng 196.41.139.168 port 80 (#0)
*   Trying 196.x.x.x... * connected
* Connected to tướng 196.x.x.x (196.x.x.x) port 80 (#0)
> POST /serve/?r=pdf/generatePdf HTTP/1.1
Host: 196.x.x.x
Accept: */*
Content-Length: 7115
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

* Recv failure: Connection reset by peer
* Closing connection #0
012 20:23:49 GMT
< Server: Apache/2.2.15 (CentOS)
< X-Powered-By: PHP/5.3.3
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
< 
* Closing connection #0

I've added in the following toe remove the mặc định header and still no luck:

curl_setopt ($c, CURLOPT_HTTPHEADER, array( 'Expect:' ) );

> Accept: */* Content-Length: 8414 Content-Type:
> application/x-www-form-urlencoded
> 
> * Recv failure: Connection reset by peer
> * Closing connection #0 r: Apache/2.2.15 (CentOS) < X-Powered-By: PHP/5.3.3 < Connection: close < Transfer-Encoding: chunked <
> Content-Type: text/html; charset=UTF-8 < 
> * Closing connection #0

asked Apr 23, 2012 at 17:55

18

Introduction

The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather phàn nàn the usual handshake.

Possible Causes

A. TCP/IP

It might be a TCP/IP issue you need to tướng resolve with your host or upgrade your OS most times connection is closed with remote server before it finished downloading the nội dung resulting in Connection reset by peer.....

B. Kernel Bug

Note that there are some issues with TCP window scaling on some Linux kernels after v2.6.17. See the following bug reports for more information:

https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.17/+bug/59331

https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.20/+bug/89160

C. PHP và CURL Bug

You are using PHP/5.3.3 which has some serious bugs too ... I would advise you to tướng work with a more recent version of PHP and CURL

https://bugs.php.net/bug.php?id=52828

https://bugs.php.net/bug.php?id=52827

https://bugs.php.net/bug.php?id=52202

https://bugs.php.net/bug.php?id=50410

D. Maximum Transmission Unit

One common cause of this error is that the MTU (Maximum Transmission Unit) size of packets travelling over your network connection has been changed from the mặc định of 1500 bytes. If you have configured a VPN this most likely must changed during configuration

D. Firewall: iptables

If you don't know your way around these guys they can cause some serious issues .. try and access the server you are connecting to tướng kiểm tra the following

  • You have access to tướng port 80 on that server

Example

 -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT`
  • The Following is at the last line not before any other ACCEPT

Example

  -A RH-Firewall-1-INPUT -j REJECT --reject-with icmp-host-prohibited 
  • Check for ALL DROP, REJECT and make sure they are not blocking your connection

  • Temporary allow all connection as see if it foes through

Experiment

Try on a different server or on a remote server ( So many không lấy phí cloud hosting online) and test the same script. If it works then my guesses are correct ... You need to tướng update your system

Others Code Related

A. SSL

If Yii::app()->params['pdfUrl'] is a url with https not including proper SSL settings can also cause this error in old version of curl

Resolution: Make sure OpenSSL is installed and enabled then add this to tướng your code

curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);

Dharman

33.1k27 gold badges99 silver badges146 bronze badges

answered Apr 27, 2012 at 11:35

8

Normally this error means that a connection was established with a server but that connection was closed by the remote server. This could be due to tướng a slow server, a problem with the remote server, a network problem, or (maybe) some kind of security error with data being sent to tướng the remote server but I find that unlikely.

Normally a network error will resolve itself given a bit of time, but it sounds lượt thích you’ve already given it a bit of time.

cURL sometimes having issue with SSL and SSL certificates. I think that your Apache and/or PHP was compiled with a recent version of the cURL and cURL SSL libraries plus I don't think that OpenSSL was installed in your trang web server.

Although I can not be certain However, I believe cURL has historically been flakey with SSL certificates, whereas, Open SSL does not.

Anyways, try installing Open SSL on the server and try again and that should help you get rid of this error.

answered Apr 30, 2012 at 18:00

I faced same error but in a different way.

When you curl a page with a specific SSL protocol.

curl --sslv3 https://example.com

If --sslv3 is not supported by the target server then the error will be

curl: (35) TCP connection reset by peer

With the supported protocol, error will be gone.

curl --tlsv1.2 https://example.com

answered Mar 19, 2018 at 19:44

2

So what is the URL that Yii::app()->params['pdfUrl'] gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to tướng accept https connections on. cURL is smart enough to tướng know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf

That's going to tướng cause the connection to tướng be terminated, when the Apache at the other over cannot tự https communication with you on that port.

You realize your first $body definition gets replaced when you mix $body to tướng an array two lines later? {Probably just an artifact of you trying to tướng solve the problem} You're also not encoding the client_url and client_id values (the former quite possibly containing characters that need escaping!) Oh and you're appending to tướng $body_str without first initializing it.

From your verbose output we can see cURL is adding a content-length header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to tướng small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:

curl_setopt ($c, CURLOPT_HTTPHEADER, 
   array("Content-Length: ". strlen($body_str))); 

Oh and there's a handy function http_build_query that'll convert an array of name/value pairs into a URL encoded string for you.

All this rolls up into the final code:

$post=http_build_query(array(
  "client_url"=>Yii::app()->params['pdfClientURL'],
  "client_id"=>Yii::app()->params['pdfClientID'],
  "title"=>$title,
  "content"=>$content));

//Open to tướng URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post))); 
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT  , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);

answered Apr 27, 2012 at 17:31

This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.

If this server is on a secure network, please have a look at firewall rules of the server.

Thanks Ganesh PNS

answered Oct 13, năm ngoái at 5:30

In my case there was problem in URL. I've use https://example.com - but they ensure 'www.' - ví when i switched to tướng https://www.example.com everything was ok. The proper header was sent 'Host: www.example.com'.

You can try make a request in firefox brwoser, persist it and copy as cURL - that how I've found it.

answered Feb 4, năm nhâm thìn at 20:59

We had the same issue, in making a websocket connection to tướng the Load Balancer. The issue is in LB, accepting http connection on port 80 and forwarding the request to tướng node (tomcat ứng dụng on port 8080). We have changed this to tướng accept tcp (http has been changed as 'tcp') connection on port 80. So the first handshake request is forwarded to tướng Node and a websocket connection is made successfully on some random( as far as i know, may be wrong) port.

below command has been used to tướng test the websocket handshake process.

curl -v -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: localhost" -H "Origin: http://LB URL:80" http://LB URL

  • Rebuilt URL to: http:LB URL/
  • Trying LB URL...
  • TCP_NODELAY set
  • Connected to tướng LB URL (LB URL) port 80 (#0)

    GET / HTTP/1.1 Host: localhost User-Agent: curl/7.60.0 Accept: / Connection: Upgrade Upgrade: websocket Origin: http://LB URL:80

  • Recv failure: Connection reset by peer
  • Closing connection 0 curl: (56) Recv failure: Connection reset by peer

tomerpacific

6,17417 gold badges40 silver badges59 bronze badges

answered Dec 4, 2019 at 5:31

This may be because that your TCP connections created by curl requests are not getting closed as soon as the job is done. This may lead to tướng an increase in the number of worker_connections an Nginx process can hold and cause the nginx server to tướng reset the new connections.

One way we can avoid the issue is by adding --retry and --retry-all-errors flags (available in the latest versions of curl) in your curl request ví that your curl retries even in the case of connection reset by peer. Also increasing the number of worker_connections in nginx.conf tệp tin can also help you avoid reaching the max limit of TCP connections.

Try to tướng close all the open TCP connections as soon as the job is done by the curl request.

answered Jul 19, 2023 at 7:05

In my case, it was proxy settings in my local VM. The request was going to tướng proxy which did not know about the server. By passing proxy solved the problem.

answered May 9, 2023 at 11:27

I my one of the application I suddenly stared getting following response.

56 Recv failure: Connection reset by peer

I was able to tướng make the request to tướng endpoint http://example.com/ws/soap?wsdl using curl.

curl -i http://example.com/ws/soap?wsdl

Also using the SoapUI I was able to tướng get the response. But using the Php code to tướng tự a curl request I was getting 56 Recv failure: Connection reset by peer

I checked in the security software logs and in the WAF logs but found nothing.

I had a code lượt thích following

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $wsdl);
curl_setopt($curl, CURLOPT_VERBOSE, 0); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArr);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestXml);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($curl, CURLOPT_TIMEOUT, 400);

$response = curl_exec($curl);
curl_close($curl);

Where I was passing the following header

$headerArr = array('Content-Type: text/xml;charset=UTF-8',
                    'SOAPAction: http://sap.com/xi/WebService/soap1.1',
                    'User-Agent: PHP-SOAP/5.2.9-2',
                    'Host: http://example.com/ws/soap?wsdl');
                

Due to tướng some upgrade some setting had changed on the destination application side. After changing the Host from http://example.com/ws/soap?wsdl to tướng example.com the issue got fixed.

$headerArr = array('Content-Type: text/xml;charset=UTF-8',
                    'SOAPAction: http://sap.com/xi/WebService/soap1.1',
                    'User-Agent: PHP-SOAP/5.2.9-2',
                    'Host: example.com');

So always try to tướng edit the header also, if you are not able to tướng find the root cause by other means.

answered Sep 15, 2023 at 16:48

Happened when curling a docker container:

docker lập cập -p 3000:3000 myimage
curl localhost:3000

Fixed by binding the docker container to tướng 127.0.0.1

docker lập cập -p 127.0.0.1:3000:3000 myimage
curl localhost:3000