Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cURL cannot connect to localhost but browser can

I'm running a Rails app locally (Thin server), and I can connect locally from the browser (localhost:3000), but when I try to use curl, I get:

curl -H 'id:1' -i 'http://localhost:3000/api/data' -v  * Hostname was NOT found in DNS cache *   Trying ::1... * Adding handle: conn: 0x7fd121808200 * Adding handle: send: 0 * Adding handle: recv: 0 * Curl_addHandleToPipeline: length: 1 * - Conn 0 (0x7fd121808200) send_pipe: 1, recv_pipe: 0 * Connection failed * connect to ::1 port 3000 failed: Connection refused *   Trying fe80::1... * Connection failed * connect to fe80::1 port 3000 failed: Connection refused * Failed to connect to localhost port 3000: Connection refused * Closing connection 0 curl: (7) Failed to connect to localhost port 3000: Connection refused 

This used to work just fine, but I recently updated to Mavericks, which I suspect may have broken something. I can also curl successfully from the web.

like image 360
jbeck Avatar asked Jan 07 '14 22:01

jbeck


People also ask

Does cURL work on localhost?

It also works for localhost, since curl will check the cache before the internal resolve and --resolve populates the DNS cache with the given entries.

Why is my localhost not working?

What Is the Localhost Refused to Connect Error? The localhost simulates a web server running on your computer. When the “localhost refused to connect” error appears, it is likely due to misconfigured port. Other common reasons include insufficient permissions and the Apache webserver not running properly.

What does cURL Connection refused mean?

What does cURL connection refused really mean? "Connection Refused" is a generic error message, it means that the connection to the server has not been successfully made.


2 Answers

This is a curl bug (a strange one), where curl fails to fall back to IPv4 if there's an IPv6 entry in /etc/hosts that doesn't respond.

You can force it to use IPv4 via the -4 option.

like image 69
Steve Clay Avatar answered Sep 20 '22 13:09

Steve Clay


Instead of

curl localhost:3000 

try

curl 0.0.0.0:3000 

It works.
If it doesn't, check the output when you start your rails server:

=> Booting WEBrick => Rails 3.2.13 application starting in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2014-10-28 15:30:08] INFO  WEBrick 1.3.1 [2014-10-28 15:30:08] INFO  ruby 2.0.0 (2014-02-24) [x86_64-darwin12.5.0] [2014-10-28 15:30:08] INFO  WEBrick::HTTPServer#start: pid=4004 port=3000 

Use the url at the end of line 2 instead of ENV['HOST']

like image 41
Marco Prins Avatar answered Sep 21 '22 13:09

Marco Prins