title: socket.error: [Errno 111] when trying to connect to a socket
body: <p>I was trying to write a code where a client connects to server on a default port number, the server then sends another port number to the client. The client now connects to the new port number.</p>
  
  <p>Client:</p>
  
  <pre><code>import socket
  import sys
  import os
  import signal
  import time
  s = socket.socket()
  s.connect(("127.0.0.1", 6667))
  line = s.recv(1024)
  if line.strip():
      port = int(line)
      s.close()
      soc = socket.socket()
      soc.connect(("127.0.0.1", port))
      print soc.recv(1024)
      soc.close()
  else:
      s.close()
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>import socket
  import sys
  import os
  import signal
  import time
  port = 7777
  s = socket.socket()
  s.bind(("127.0.0.1", 6667))
  s.listen(0)
  sc, address = s.accept()
  print address
  sc.send(str(port))
  sc.close()
  s.close()
  sock = socket.socket()
  sock.bind(("127.0.0.1", port))
  soc, addr = sock.accept()
  print addr
  soc.send("Success")
  soc.close()
  sock.close()
  </code></pre>
  
  <p>When I execute this code, I am getting following errors on client and server sides.</p>
  
  <p>Server:</p>
  
  <pre><code>('127.0.0.1', 36282)
  Traceback (most recent call last):
    File "server.py", line 17, in &lt;module&gt;
      soc, addr = sock.accept()
    File "/usr/lib/python2.7/socket.py", line 202, in accept
      sock, addr = self._sock.accept()
  socket.error: [Errno 22] Invalid argument
  </code></pre>
  
  <p>Client:</p>
  
  <pre><code>Traceback (most recent call last):
    File "client.py", line 13, in &lt;module&gt;
      soc.connect(("127.0.0.1", port))
    File "/usr/lib/python2.7/socket.py", line 224, in meth
      return getattr(self._sock,name)(*args)
  socket.error: [Errno 111] Connection refused
  </code></pre>
  
  <p>Can someone explain me the reason for these errors and provide a solution for these errors.</p>