Urlopen error errno 111 connection refused

In this article, we will learn what is the ConnectionRefusedError, basically this error indicates that the client is unable to connect to the port on the system running the server script.
  1. Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python
  2. How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python
  3. Conclusion

ConnectionRefusedError: [Errno 111] Connection Refused

This error indicates that the client cannot connect to the port on the server script’s system. Since you can ping the server, it should not be the case.

This might be caused by many reasons, such as improper routing to the destination. The second possibility is that you have a firewall between your client and server, which may be either on the server or the client.

There shouldn’t be any routers or firewalls that may stop the communication since, based on your network addresses, both the server and the client should be on the same Local Area Network.

Why the ConnectionRefusedError: [Errno 111] Connection refused Occurs in Python

This error arises when the client cannot access the server because of an invalid IP or port or if the address is not unique and used by another server.

The connection refused error also arises when the server is not running, so the client cannot access the server as the server should accept the connection first.

Code example:

# server code
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind((host, port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("Meeting is at 10am")
    c.close()
# client code
import socket

s = socket.socket()
host = '192.168.1.2'
port = 1717

s.connect((host,port))
print(s.recv(1024))
s.close

Output:

socket.error: [Errno 111] Connection refused

How to Solve the ConnectionRefusedError: [Errno 111] Connection refused in Python

Try to keep the receiving socket as accessible as possible. Perhaps accessibility would only take place on one interface, which would not impact the Local Area Network.

On the other hand, one case can be that it exclusively listens to the address 127.0.0.1, making connections from other hosts impossible.

Code example:

import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.listen(5)
while True:
    c,addr = s.accept()
    print("Got connection ", addr)
    c.send("The Meeting is at 10 am")
    c.close()
import socket

s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))

s.connect((host, port))
print(s.recv(1024))
s.close()

Output:

Got connection('192.168.1.2')
The meeting is at 10 am

When you run the command python server.py, you will receive the message Got connection. At the same time when you run the command python client.py, you will receive a message from the server.

The DNS resolution can be the other reason behind this problem. Since the socket.gethostname() returns the hostname, an error will be returned if the operating system cannot translate it to a local address.

The Linux operating system can edit the host file by adding one line.

host = socket.gethostname()
port = 1717
s.bind((host,port))

Use gethostbyname

host = socket.gethostbyname("192.168.1.2")
s.bind((host, port))

Thus, you must use the identical technique on the client and server sides to access the host. For instance, you would apply the procedure described above in a client’s case.

You can also access through local hostname hostnamehost = socket.gethostname() or specific name for local host host = socket.gethostbyname("localhost").

host = socket.gethostname()
s.connect((host, port))
host = socket.gethostbyname("localhost")
s.connect((host, port))

Conclusion

ConnectionRefusedError in Python arises when the client cannot connect to the server. Several reasons include the client not knowing the IP or port address and the server not running when the client wants to connect.

There are several methods mentioned above to resolve this connection issue.

DigitalOcean Referral Badge
Start your VPS now with FREE $100 credit.

As a versatile programming language, Python can also be used to create a networked application. Game servers, web servers, microservices, and instant messaging are some of the possible use cases for Python.

With Python, you can build a client app that connects to a certain server to do a certain thing (such as a third-party music streaming client) or a server that accepts connections from clients (such as a web server for dynamic health data processing).

Or, even better, to avoid having to use multiple tech stacks, why not create servers and clients entirely using Python? It’s certainly doable and even practical in some cases.

Python handles network connections gracefully, and if you develop with Python, you can specify the type of communication you want in your application. Uploading and downloading files is also a breeze with Python apps.

That being said, there are a few cases where developers/users can’t get into their web/services due to the error “ConnectionRefusedError: [Errno 111] Connection refused”. It can lead users that there is something wrong with the apps. We’re going to show you how to solve this issue.

What Caused the Error?

This error is caused by the client’s inability to access the specified port in the computer or network. Sometimes, ports are blocked in school or library networks to avoid illicit communication. This is especially true if your port is far from the commonly-used ports.

How to Fix It?

If you know the port number of your Python application, you can try whitelisting the port in your own network or asking the school/library technician to allow your specific port.

This error can also happen if the server is offline or not accepting a connection. In this case, you will need to start the server manually in the meantime.

Services such as Pingdom make it easy to monitor server availability, or you can explore things such as Cron jobs to monitor your service. However, if possible, reduce things that run in your service to maintain good security posture and application performance.

In short, when you’re facing the error “ConnectionRefusedError: [Errno 111] Connection refused”, it is a normal thing. A reboot of your computer might solve the problem.

If it is not fixed, you might need to whitelist the used port in the firewall. Or, if the problem persists, it is time to take a look at your server(s).

Are they overwhelmed? Do you need new equipment? It is a question only you, as a developer, could answer.

We are a bunch of people who are still continue to learn Linux servers. Only high passion keeps pushing us to learn everything.

This is the error message

ConnectionRefusedError Traceback (most recent call last)
/usr/lib/python3.5/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1253 try:
-> 1254 h.request(req.get_method(), req.selector, req.data, headers)
1255 except OSError as err: # timeout error

/usr/lib/python3.5/http/client.py in request(self, method, url, body, headers)
1105 «»»Send a complete request to the server.»»»
-> 1106 self._send_request(method, url, body, headers)
1107

/usr/lib/python3.5/http/client.py in _send_request(self, method, url, body, headers)
1150 body = _encode(body, ‘body’)
-> 1151 self.endheaders(body)
1152

/usr/lib/python3.5/http/client.py in endheaders(self, message_body)
1101 raise CannotSendHeader()
-> 1102 self._send_output(message_body)
1103

/usr/lib/python3.5/http/client.py in _send_output(self, message_body)
933
—> 934 self.send(msg)
935 if message_body is not None:

/usr/lib/python3.5/http/client.py in send(self, data)
876 if self.auto_open:
—> 877 self.connect()
878 else:

/usr/lib/python3.5/http/client.py in connect(self)
848 self.sock = self._create_connection(
—> 849 (self.host,self.port), self.timeout, self.source_address)
850 self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

/usr/lib/python3.5/socket.py in create_connection(address, timeout, source_address)
710 if err is not None:
—> 711 raise err
712 else:

/usr/lib/python3.5/socket.py in create_connection(address, timeout, source_address)
701 sock.bind(source_address)
—> 702 sock.connect(sa)
703 return sock

ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

URLError Traceback (most recent call last)
<ipython-input-2-46fb38c4ce3b> in <module>()
7
8 # open and save the zip file onto computer
—-> 9 url = urlopen(URL)
10 output = open(‘zipFile.zip’, ‘wb’) # note the flag: «wb»
11 output.write(url.read())

/usr/lib/python3.5/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
161 else:
162 opener = _opener
—> 163 return opener.open(url, data, timeout)
164
165 def install_opener(opener):

/usr/lib/python3.5/urllib/request.py in open(self, fullurl, data, timeout)
464 req = meth(req)
465
—> 466 response = self._open(req, data)
467
468 # post-process response

/usr/lib/python3.5/urllib/request.py in _open(self, req, data)
482 protocol = req.type
483 result = self._call_chain(self.handle_open, protocol, protocol +
—> 484 ‘_open’, req)
485 if result:
486 return result

/usr/lib/python3.5/urllib/request.py in _call_chain(self, chain, kind, meth_name, args)
442 for handler in handlers:
443 func = getattr(handler, meth_name)
—> 444 result = func(
args)
445 if result is not None:
446 return result

/usr/lib/python3.5/urllib/request.py in http_open(self, req)
1280
1281 def http_open(self, req):
-> 1282 return self.do_open(http.client.HTTPConnection, req)
1283
1284 http_request = AbstractHTTPHandler.do_request_

/usr/lib/python3.5/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1254 h.request(req.get_method(), req.selector, req.data, headers)
1255 except OSError as err: # timeout error
-> 1256 raise URLError(err)
1257 r = h.getresponse()
1258 except:

URLError: <urlopen error [Errno 111] Connection refused>

I’m trying to run an Ansible playbook to create a new local user account on a Big-IP VE running 13.1.3.4 using the bigip_user module. I’m able to run tasks using bigip_device_info and bigip_config modules successfully, but whenever I try to run a playbook with a module to change settings (i.e. bigip_user or bigip_snmp_community) it errors out with the message: «An exception occurred during task execution. To see the full traceback, use -vvv. The error was: urllib.error.URLError: <urlopen error [Errno 111] Connection refused>»

I’m new to Ansible on Big-IP platform. Any help on this is greatly appreciated.

Playbook:

---
- name: Add users playbook
  hosts: "{{ devices }}"
  strategy: free
  order: sorted
  connection: local
  gather_facts: no
  become: no
  become_method: enable
  ignore_errors: no

  collections:
    - f5networks.f5_modules

  vars:
    provider:
      server: "{{ ansible_host }}"
      user: <username>
      password: <password>
      validate_certs: no
      server_port: 443

  tasks:
  - name: Add or update the user
    bigip_user:
  provider: "{{ provider }}"
  username_credential: user
  password_credential: password
  update_password: always
  full_name: User
  shell: bash
  partition_access:
    - all:admin
  state: present
    delegate_to: localhost

Error:

The full traceback is:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/urllib/request.py", line 1350, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/usr/local/lib/python3.7/http/client.py", line 1277, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/local/lib/python3.7/http/client.py", line 1323, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.7/http/client.py", line 1272, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/local/lib/python3.7/http/client.py", line 1032, in _send_output
    self.send(msg)
  File "/usr/local/lib/python3.7/http/client.py", line 972, in send
    self.connect()
  File "/usr/local/lib/python3.7/http/client.py", line 1439, in connect
    super().connect()
  File "/usr/local/lib/python3.7/http/client.py", line 944, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/local/lib/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/usr/local/lib/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

Thanks,

-Edson

Понравилась статья? Поделить с друзьями:
  • Urlopen error errno 11003 getaddrinfo failed
  • Usbsafe fatal error
  • Urlmon dll ошибка
  • Usbmux error 92 checkra1n
  • Urllib2 httperror http error 501 https required