cURL cannot connect to localhost but browser can

jbeck picture jbeck · Jan 7, 2014 · Viewed 21.5k times · Source

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.

Answer

Steve Clay picture Steve Clay · Mar 24, 2014

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.