title: How can I debug what is causing a connection refused or a connection time out?
body: <p>I have the following code that has worked for about a year:</p>
  
  <pre><code>import urllib2
  
  req = urllib2.Request('https://somewhere.com','&lt;Request&gt;&lt;/Request&gt;')
  data = urllib2.urlopen(req)
  print data.read()
  </code></pre>
  
  <p>Lately, there have been some random errors:</p>
  
  <ul>
  <li><code>urllib2.URLError: &lt;urlopen error [Errno 111] Connection refused&gt;</code></li>
  <li><code>&lt;urlopen error [Errno 110] Connection timed out&gt;</code></li>
  </ul>
  
  <p>The trace of the failure is:</p>
  
  <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
    File "test.py", line 4, in &lt;module&gt;
      data = urllib2.urlopen(req).read()
    File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
      return _opener.open(url, data, timeout)
    File "/usr/lib/python2.7/urllib2.py", line 400, in open
      response = self._open(req, data)
    File "/usr/lib/python2.7/urllib2.py", line 418, in _open
      '_open', req)
    File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain
      result = func(*args)
    File "/usr/lib/python2.7/urllib2.py", line 1215, in https_open
      return self.do_open(httplib.HTTPSConnection, req)
    File "/usr/lib/python2.7/urllib2.py", line 1177, in do_open
      raise URLError(err)
  urllib2.URLError: &lt;urlopen error [Errno 111] Connection refused&gt;
  </code></pre>
  
  <p>The above errors happen randomly, the script can run successfully the first time but then fails on the second run and vice versa.</p>
  
  <p><strong>What should I do to debug and figure out where the issue is coming from?</strong>  How can I tell if the endpoint has consumed my request and returned a response but never reached me?</p>
  
  <h2>With telnet</h2>
  
  <p>I just tested with telnet, sometimes it succeeds, sometimes it doesn't, just like my Python.</p>
  
  <p>On success:</p>
  
  <pre class="lang-none prettyprint-override"><code>$ telnet somewhere.com 443
  Trying XXX.YY.ZZZ.WWW...
  Connected to somewhere.com.
  Escape character is '^]'.
  Connection closed by foreign host.
  </code></pre>
  
  <p>On a refused connection:</p>
  
  <pre class="lang-none prettyprint-override"><code>$ telnet somewhere.com 443
  Trying XXX.YY.ZZZ.WWW...
  telnet: Unable to connect to remote host: Connection refused
  </code></pre>
  
  <p>On a timeout:</p>
  
  <pre class="lang-none prettyprint-override"><code>$ telnet somewhere.com 443
  Trying XXX.YY.ZZZ.WWW...
  telnet: Unable to connect to remote host: Connection timed out
  </code></pre>