I am trying to write a program for file transfer using sockets. The server end of the code is running fine. However, in the client side I get the following error
Traceback (most recent call last):
File "client.py", line 54, in <module>
uploadFiles(directory)
File "client.py", line 36, in uploadFiles
transferFile(fname)
File "client.py", line 13, in transferFile
cs.connect((HOST, 36258))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
My code is as follows
import os
import socket
def transferFile(fname):
HOST = '127.0.0.1'
CPORT = 36258
MPORT = 36250
FILE = fname
cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cs.connect((HOST, 36258))
cs.send("SEND " + FILE)
cs.close()
ms = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ms.connect((HOST, MPORT))
f = open(FILE, "rb")
data = f.read()
f.close()
ms.send(data)
ms.close()
def uploadFiles(directory):
home = os.getenv("HOME")
folder = str(home + "/" + directory)
os.chdir(folder)
dirList = os.listdir(folder)
print dirList
for fname in dirList:
if fname.endswith('.bin'):
transferFile(fname)
os.chdir(os.getenv("HOME"))
directory = "testdownload"
if not os.path.exists(directory):
os.makedirs(directory)
os.chdir(directory)
uploadFiles(directory)
I tried looking for help on Google and other posts on Stack Overflow, none of them helped. Can someone please help me?
The line numbers may be different since I pasted only some part of the code
Generally, in python, the connection error is not something that you will face every day, but it can sometimes happen due to various reasons. One such reason is the connection Refuse. This causes the generation of ConnectionRefusedError errno 111 connection refused message. If you are facing this error message in your coding, this might help you.
What is socket error?
A socket programming in python is used to form a bidirectional communications channel. It is generally a process of making the two unrelated network nodes communicate with each other by making a connection. This connection can be made if you know the IP address of the server.
What is ConnectionError?
Whether you are someone new to the python language or not, you must be aware of the term connection error. As suggested by the name, it is a class of exception errors related to the errors generated due to issues in the connection. It is a type of socket error that is observed in many other libraries and platforms.
In python, the ConnectionError is generally referred to as an error generated by the failure in any of the internal connections that are the connection between the application and the DBMS server mediating a peer. This type of error can be caused by various failures, such as local errors caused by the errors reported directly to the user interface programs, then local and remote errors caused while trying to connect from the local communication server to the remote communication server and the server installation. These ConnectionErrors also report directly to the applications.
Types Of ConnectionError
There are mainly three subclasses of ConnectionError such as ConnectionAbortedError, ConnectionResetError, and ConnectionRefusedError. These errors generally arise when the error is raised due to the attempt the interruption in connection with the actions of peers.
The ConnectionRefusedError errno 111 connection refused is a subclass of the ConnectionError which is caused when the peer refuses the attempts for the connection between the application and the server. This type of error corresponds to errno ECONNREFUSED messages.
The ConnectionRefusedError errno 111 connection refused is generated when the initial SYN packet to the host to be connected was responded with an RST packet instead of a SYN+ACK packet. This resulted in the declination of the program on the remote computer that needed to be connected.
This type of error can cause by many libraries and computing platforms, but the solutions to this problem are similar.
The generation of the error can be understood efficiently by using an example:
As the connection has to be made from both end so it is done in two parts:
The Server script:
The client script:
These codes might seem good, but this will result in the socket.error: [Errno 111] Connection refused message.
How to solve the ConnectionRefusedError errno 111 connection refused?
As this is a connection-based error, so the errors have to be checked on both ends that is, on the client and the server end. The ConnectionRefusedError errno 111 connection refused can be resolved using one of the following reasons.
Checking the connection
- Ensure the IP address is of the client, and both servers are on the same LAN. If the servers are not on the same router or firewall, then you may face traffic blocking.
- Make sure that the port is listening to the server and if not then try “netstat -ntulp”.
- Make sure that you are accepting the connections to the server.
- Make sure you have access to the port server of the client.
Selectively restrict the listening socket
In the example for the generation of the ConnectionRefusedError by the server you can see that there is a line as follows:
host = socket.gethostname() #Get the local machine name
port = 98406 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
Instead of the above code, you can try:
port = 98406 # Reserve a port for your service
s.bind(('', port)) #Bind to the port
This way, the listening socket will not be too restricted and will ensure the connection precisely on both ends.
Proper guidance to get an IP address
To avoid ConnectionRefusedError errno 111 connection refused while coding you need to make sure to get the right IP address for that you have to put the hostname and port number for the receiver end correctly.
Due to DNS resolution, the hostname might not get translated into the local address and returned properly. So instead of the usual code:
host = socket.gethostname() #Get the local machine name
port = 98406 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
You can try the code below.
host = socket.gethostbyname("localhost")
s.connect((host, port))
FAQ
How do you fix a socket error?
As the ConnectionRefusedError errno 111 connection refused is a type of socket error, resolving this may help in resolving the former error.
- This error can be fixed by specifying the port number for which you can use the following code:
m SimpleHTTPServer (Port Number)
- You can also free up the port by terminating the previous programs.
What is the socket address in computer networks?
The socket address is a crucial part of establishing the connection. It is generally a combination of two identifiers, that is both IP address and port number. It is defined in a header where it is specified by a data structure.
Conclusion
The ConnectionRefusedError errno 111 connection refused is a socket error that results when there is a failure in the establishment of connection when the connection is refused. Which can later be resolved by managing the data necessary for establishing the connection.
References
- Dizzy coding
- GeeksforGeeks socket programming
To learn more about some common errors follow python clear’s errors section.
- Why the
ConnectionRefusedError: [Errno 111] Connection refusedOccurs in Python - How to Solve the
ConnectionRefusedError: [Errno 111] Connection refusedin Python - Conclusion
![ConnectionRefusedError: [Errno 111] Connection Refused](https://www.delftstack.com/img/Python/feature%20image%20-%20connectionrefusederror%20[errno%20111]%20connection%20refused.png?ezimgfmt=ng%3Awebp%2Fngcb5%2Frs%3Adevice%2Frscb5-1)
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.
Connectionrefusederror: [errno 111] connection refused is an error message that the Python “socket()” function will show when it cannot connect to the server due to an error or setting from your client or the server.
This article will teach you why you’re seeing this error in your Python code and how you can fix it. To ensure that you’ll get the best from this article, we’ll use theory and practical code examples to explain the solutions to this error message.
Now, grab your computer, and let’s fix the connection issues in the “socket()” function in Python.
Contents
- Why the “Socket()” Function Shows a Connection Refused Error?
- – The Server Is Offline
- – You’re Connecting to the Wrong Port
- – The Server Cannot Accept New Connections
- – You’re Connecting to the Wrong Ip Address
- – A Firewall Is Blocking Your Connection
- How To Connect the “Socket()” Function Without an Error
- – Ensure the Server Is Online
- – Connect to the Correct Port of the Server
- – Wait for the Server To Respond
- – Use the Correct Ip Address of the Server
- – Update the Firewall Rules To Allow Your Connection
- Conclusion
- References
Why the “Socket()” Function Shows a Connection Refused Error?
The “socket()” function showed a connection refused error because of the following:
- The server is offline
- You’re connecting to the wrong port
- The server cannot accept new connections
- You’re connecting to the wrong IP address
- A firewall is blocking your connection
– The Server Is Offline
When a server is offline, any connection attempt to the server using the “socket()” function in Python will result in the “connection refused” error. If it’s a remote server, it could be down for maintenance and if it’s a local web server, you could have forgotten to switch it on.
For example, the following Python code should connect to “localhost” on port 80, but if “localhost” is offline, you’ll get the “connectionrefusederror”.
# Create a socket connection using Ipv4
# protocol and TCP protocol.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the localhost on port 8080
client_socket.connect((‘localhost’, 8080))
– You’re Connecting to the Wrong Port
A connection to a server using the wrong port number will result in the “connectionrefusederror” because that server is not listening on that port.
For example, the following is a Python script that’s trying to connect to an Apache web server using port 801. This port number is not valid because the server has a different port number.
# Create a socket connection using Ipv4
# protocol and TCP protocol.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Trying to connect to a local Apache server
# using port 801 results in an error.
client_socket.connect((‘localhost’, 801))
The following is another example, and this time we have a server and client code. When you run the server’s code, it will listen on port 8080, but the client’s code is trying to connect to the wrong port.
import socket
# Create a server and set it to listen
# on 127.0.0.1 and port 8080
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((‘127.0.0.1’, 8080))
server_socket.listen(5)
# client.py
import socket
# Error: Connecting with a different port.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((‘127.0.0.1’, 80))
– The Server Cannot Accept New Connections
When a server cannot accept new connections, it will refuse your connection, and this happens if the server is experiencing multiple connection requests. You can observe this using the following Python script that will make multiple concurrent connections to a local Apache web server that’s running on port 80.
In our test environment, the server accepted the first 351 connection requests, and it started rejecting them from the 352nd. This happens because the server was overwhelmed after the 351 requests, and it stopped accepting new ones.
# The number of connections that
# you want to open to the server.
num_connections = 352
server_address = (‘localhost’, 80)
# Create a socket for each connection
sockets = [socket.socket(socket.AF_INET, socket.SOCK_STREAM) for _ in range(num_connections)]
# Connect each socket to the server
for a_socket in sockets:
try:
a_socket.connect(server_address)
print(“Connected to server”)
except ConnectionRefusedError:
print(“Connection refused!”)
– You’re Connecting to the Wrong Ip Address
Servers do have an “IP address” that you can connect to, and you’ll get a “connectionrefusederror” if you don’t use this address in the “socket()” function. An example is the following Python script that’s trying to connect to the local Apache web server using the IP address “127.1.0.1” on port 8080.
You’ll get the “connectionrefusederror” when you run this code because the IP address is wrong and 8080 is not the default port for a local Apache web server.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Trying to connect to a local Apache server
# using IP address 127.1.0.1 and port 8080 will fail.
client_socket.connect((‘127.1.0.1’, 8080))
– A Firewall Is Blocking Your Connection
A connection to a server that has blocked incoming connections will lead to the “connectionrefusederror” when you’re using the “socket()” function in Python.
Some servers do this for security reasons, and others could have blocked the port number that you’re trying to connect to. The latter mostly occurs when your client is on a different network, and you want to connect to a server on another network.
How To Connect the “Socket()” Function Without an Error
The “socket()” function can connect without an error if you do the following:
- Ensure the server is online
- Connect to the correct port of the server
- Wait for the server to respond
- Use the correct IP address of the server
- Update the firewall rules to allow your connection
– Ensure the Server Is Online
Your first course of action when you get the “connectionrefusederror” is to check if the server is online. If it’s an online server, you can put the server’s hostname on a service like “IsItDownRightNow?”.
Another option is the following Python script that has a timeout for the server to respond. So, if the server did not respond after the timeout, that means the server is offline or you have made a mistake in the IP address or port number.
def is_it_online(server_address, port_number):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set a connection timeout
s.settimeout(10)
try:
# Try to connect to the server
s.connect((server_address, port_number))
print(“The server is online.”)
except socket.timeout:
print(“Server is offline.”)
except:
print(“Error: unable to connect to the server”)
s.close()
is_it_online(“localhost”, 80)
– Connect to the Correct Port of the Server
Making a successful connection to a server using the “socket()” function requires that you specify the correct port number.
The following is the correct script that will connect to a local Apache web server on port 80, and it’s an update to the earlier script that used port 801. The latter caused the “connectionrefusederror”, but 80 will not because it’s the correct port number.
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# The correct and default port for a local
# Apache web server is 80 or 443.
client_socket.connect((‘localhost’, 80))
Also, the following is the updated version of the client-server code. This time, we ensure that the client is connecting to port 8080 and not port 80:
import socket
# The server code remains the same
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((‘127.0.0.1’, 8080))
server_socket.listen(5)
# client.py
import socket
# Update: We changed the port number to 8080
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((‘127.0.0.1’, 8080))
– Wait for the Server To Respond
When a server is experiencing a high load because of concurrent connections, you can wait for it to respond. That waiting time is not in your control, but if it’s your server, you can add more resources like Central Processing Units, and memory to handle the increased load.
– Use the Correct Ip Address of the Server
If a server is listening on a specific IP address, ensure that you’re using that address in your Python script. Earlier, we showed you a code that’s trying to connect to a local Apache web server using “127.1.0.1” and port 8080.
Now, the following is the correct version because a local Apache web server listens on “127.0.0.1” and port 80 or port 443.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Fix: Use 127.0.0.1 and port 80 for the
# local Apache web server.
if s.connect_ex((‘127.0.0.1’, 80)) == 0:
print(“Connected to the server!”)
# Create and send a request to the server.
request = “GET / HTTP/1.1rnHost: 127.0.0.1rnrn”
s.send(request.encode())
response = s.recv(1024)
# Print the request.
print(“We got the following response from the server: “, response.decode())
s.close()
else:
print(“Connection refused.”)
Finally, the following is the sample response that we got from our test Apache web server:
We got the following response from the server: HTTP/1.1 302 Found
Date: Tue, 10 Jan 2023 18:41:57 GMT
Server: Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/8.1.6
X-Powered-By: PHP/8.1.6
Location: http://127.0.0.1/dashboard/
Content-Length: 0
Content-Type: text/html; charset=UTF-8
– Update the Firewall Rules To Allow Your Connection
If you’re certain that it’s a firewall that’s blocking your connection request to the remote server, you can contact the server admin to reconfigure the firewall.
Or, you can use a different port that the firewall will allow, and you can do the same if it’s a local firewall that’s blocking your connection. For example, if you’re on a Windows system, you can access the “Windows Firewall with Advanced Security” and see if it’s blocking connection to the remote server.
Conclusion
This article explained why you’re seeing the “connectionrefusederror” when using the “socket()” function in Python and how you can fix the error. The following is a quick summary of what we talked about:
- When you’re trying to connect to an offline server using the “socket()” function, you’ll encounter the “connectionrefusederror”.
- Any attempt to connect to a wrong IP address or port number will cause the server to refuse your connection.
- To solve the “connectionrefusederror” in Python, ensure the server is online and that you’re connecting using the correct IP address and/or port number.
- If a server is overwhelmed, and it’s refusing your connection, wait for a while and try again.
- If it’s a firewall that’s blocking your connection, reconfigure it or have the administrator allow you access.
You can apply what you’ve learned in this article in your projects and teach your friends that are facing the same error. If the error happens in the future, you can read our article again.
References
- https://docs.python.org/3/library/socket.html
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
Would you like to learn more about the “ConnectionRefusedError: [Errno 111] Connection refused” error when developing in Python, as well as how to troubleshoot it? 🤔
The ConnectionRefusedError: [Errno 111] connection refused is a common error message that can be encountered while working with network programming in Python. This error can occur when a program is trying to establish a connection to a remote server or service, but the connection is being refused by the server.
In this article, we will discuss why ConnectionRefusedError: [Errno 111] connection refused error occurs and the steps on how to resolve it. So without further ado, let’s dive deep into the topic and see some Solutions! 👇
Table of Contents
- Why Does the ConnectionRefusedError [Errno 111] Connection Refused Error Occur?
- How to Fix the ConnectionRefusedError: [Errno 111] Connection Refused Error?
- Other Fixes for the “ConnectionRefusedError: [Errno 111] Connection Refused” Error
Why Does the ConnectionRefusedError [Errno 111] Connection Refused Error Occur?
1. Network Issue
This could be caused by a number of factors, such as a network outage, misconfiguration of the network settings, or problems with the routing of data packets. In order to resolve this type of error, it is essential first to ensure that the network is configured correctly and functioning as expected. This can be done by checking the network settings and performing a network diagnosis to identify any potential issues.
2. Firewall Restrictions
Firewalls are used to protect networks by controlling the flow of traffic between different devices and services. If a firewall is preventing the connection, it can result in the ConnectionRefusedError error message. In order to resolve this issue, it is necessary to configure the firewall to allow the connection to the desired service or application.
3. Incorrectly Configured Network Settings
In addition to network and firewall issues, the ConnectionRefusedError in Python can also be caused by incorrect configuration settings. This could include using the wrong port number or protocol or specifying the wrong hostname or IP address.
In order to resolve this issue, it is important to review the configuration settings and ensure that they are correct and match the requirements of the application or service being used.
Client Code
If you are writing client code to connect to a server, the error may occur in the following code:
Code
import socket s = socket.socket() host = '192.168.17.8’' port = 1717 s.connect((host,port)) print(s.recv(1024)) s.close
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("Connected ", addr)
c.send("You are invited to an event")
c.close()
Output
socket.error: [Errno 111] Connection refused
The ConnectionRefusedError: [Errno 111] Connection refused error in Python can occur in different parts of your code where you are attempting to establish a connection with a server or service. Here is an example of how to fix this error:
Server Code
import socket
s = socket.socket()
host = socket.gethostname()
port = 1717
s.bind(('', port))
s.listen(5)
while True:
c,addr = s.accept()
print("Connected ", addr)
c.send("You are invited to an event")
c.close()
Client code
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.17.8')
You are invited to an event.
You will see the message Connected when you type the command python server.py. You will get a message from the server when you run the python client.py command simultaneously.
Another potential cause of this issue is DNS resolution. Since socket.gethostname() only delivers the hostname, if the operating system is unable to convert it to a local address, an error will be returned.
Other Fixes for the “ConnectionRefusedError: [Errno 111] Connection Refused” Error
Now that we know the reasons behind the ConnectionRefusedError: [Errno 111] connection refused error, let’s explore some ways to fix it.
1. Check if the Server is Running
The first thing you should do when you encounter the ConnectionRefusedError: [Errno 111] connection refused error is to check if the server is running. You can do this by pinging the server or by checking its status on the server console. If the server is not running, start it and try connecting again.
2. Check the Firewall Settings
If the server is running, the next thing you should check is the firewall settings. Firewalls are designed to protect the server from unauthorized access, and they can block connections from certain IP addresses or ports. If your client is blocked by the firewall, you will get this error message.
To fix this issue, you can temporarily disable the firewall or add a rule to allow connections from your IP address or port.
3. Verify the Connection Details
If the server is running and the firewall settings are correct, the next thing you should check is the connection details. Make sure that you are using the correct protocol (e.g., HTTP, HTTPS, TCP, UDP) and the correct port number for the service you are trying to connect to. Double-check your username and password, and make sure that they are correct.
4. Try Connecting From a Different Network or Computer:
If you have tried all of the above solutions and you are still getting the “ConnectionRefusedError, you should try connecting from a different network or computer. This will help you determine if the problem is with your network or computer or if the issue is with the server configuration.
Conclusion
In conclusion, the ConnectionRefusedError: [Errno 111] Connection refused error is a common error that occurs when a client is unable to connect to a server. This error can be caused by a number of factors, including server downtime, firewall restrictions, or incorrect configuration settings.
To fix this error, you can check if the server is running, verify the firewall settings, double-check the connection details, or try connecting from a different network or computer. By taking these steps, you can resolve the ConnectionRefusedError: [Errno 111] Connection refused error and ensure that your network-based applications are working as intended.
If you’ve found this article helpful, don’t forget to share it.





