Python - [Errno 111] Connection refused on client side of the connection - python

I'm trying to create a chat between client and server written in Python, using SSL protocols with mutual authentication (i.e: server authenticates client and client authenticates server using certificates). My host machine is being used as the server, and my laptop is the client.
When attempting to connect to my host ip, I keep getting this error on my laptop:
Traceback (most recent call last):
File "/home/icarus/Codes/RealtimeChat/Chat.py", line 88, in <module>
main()
File "/home/icarus/Codes/RealtimeChat/Chat.py", line 75, in main
connection(ip, port, SSLSock)
File "/home/icarus/Codes/RealtimeChat/Chat.py", line 35, in connection
sock.connect((ip, port))
File "/usr/lib/python3.10/ssl.py", line 1375, in connect
self._real_connect(addr, False)
File "/usr/lib/python3.10/ssl.py", line 1362, in _real_connect
super().connect(addr)
ConnectionRefusedError: [Errno 111] Connection refused
And in the server - which was supposed to print a message saying that a connection was refused - nothing happens, it keeps listening for connections as if nothing happened
Connection function on client side:
def connection(ip, port, sock):
try:
sock.connect((ip, port))
print(f"Connected with {ip}")
except Exception as e:
print("Connection failed: ", e)
sock.close()
Server side:
def acceptConnection(self):
while True:
con, senderIP = self.sock.accept()
# Attempting to wrap connection with SSL socket
try:
SSLSock = self.getSSLSocket(con)
# If exception occurs, close socket and continue listening
except Exception as e:
print("Connection refused: ", e)
con.close()
continue
print(f"{senderIP} connected to the server")
# Adding connection to clients list
self.clients.append(SSLSock)
# Initializing thread to receive and communicate messages
# to all clients
threading.Thread(target=self.clientCommunication, args=(SSLSock, ), daemon=True).start()
This is the main function on my server:
def main():
serverIP = "127.0.0.1"
port = int(input("Port to listen for connections: "))
server = Server()
server.bindSocket(serverIP, port)
server.socketListen(2)
server.acceptConnection()
Everything works fine when I connect from my localhost (e.g I open a server on my host machine on one terminal and use another one on the same machine to connect to it). Both machines have the required certificates to authenticate each other, so I don't think that's the problem. Also, without the SSL implementation, the connection between this two different computers was refused by the server
I've tried using sock.bind('', port) on server side, disabling my firewall, used telnet 127.0.0.1 54321 (on my host machine) to check if the connection was working on the specified port (and it is), and also on the client machine (which showed that the connection was refused). I also tried running both scripts with admin privileges (sudo), but it also didn't work. Any suggestions?

I found what was wrong: I was trying to connect to my public IP address (which I found by searching for "What is my ip" on Google), but instead what should be done is to connect to the private IP address (I guess that's the correct name), and you can see yours using ifconfig on Linux and Mac and ipconfig on Windows using a terminal. By doing this, I could connect two computers that are on my network to my desktop server, I still haven't tested for computers in different networks, but the problem has been solved.

Related

SSL raises version error only on re-connect attempt?

We have a server and client both running python3.
The client connects to the server and authenticates upon initialisation of the client. This completes without issue.
However, if the connection drops, the client catches the error (the socket.recv returning 0) and attempts to re-run the code that connects to the server).
The server recieves the initial request whilst listening on its given recieving socket and then once making a connection the next recv call raises the following error:
File "/usr/lib64/python3.7/ssl.py", line 1056, in recv
return self.read(buflen)
File "/usr/lib64/python3.7/ssl.py", line 931, in read
return self._sslobj.read(len)
ssl.SSLError: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:2570)
Why would this succeed upon the first connection but then raise this error thereafter? If the client is closed and restarted the error is avoided upon the next connection. However, if the server is closed and the client tries to connect once the server restarts this error is encountered.
At the client end the following error is raised:
File "\Our_Code", line 100, in make_connection
data = self.ssl_sock.recv(1024)
File "C:\Users\Home\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1226, in recv226, in recv
return self.read(buflen) 101, in read
File "C:\Users\Home\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1101, in read
return self._sslobj.read(len)
ssl.SSLError: [SSL] internal error (_ssl.c:2633)
This exact formultation suggests to me that the issue is actually with the client and some data that it is saving between reconnects. But it overwrites the sockets for a new connection so I thought all data from the previous connection would be discarded?
The connection function is as:
import socket
import ssl
def make_connection(self, email, password):
try:
self.ssl_sock = []
HOST = "9:9:99:999" # The server's hostname or IP address (not our actual IP)
PORT = 5432 # The port used by the server (not our actual port)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
self.ssl_sock = self.context.wrap_socket(sock)
password = password.encode('utf-8').strip()
password = base64.b64encode(password).decode("utf-8")
tcp_string = (f"^{email}*{password}$")
tcp_string = tcp_string.encode('utf-8')
self.ssl_sock.sendall(tcp_string)
data = self.ssl_sock.recv(1024)
data = data.decode('utf-8')
if data == "^good_connect$":
return True
else:
return False
except Exception:
print(f"make_connection - {traceback.format_exc()}")
I'm still fairly new to python and particularly networking, so I suspect I have made a rookie error. But so far all my searches have returned the obvious, that the TLS version is wrong, but the fact that it authenticates fine on the initial connection suggests to me that that isn't the case.
I'm happy to answer any questions I can about the situation.

Python socket server port forwarding with ngrok

I am making a cli-chat system with python, sockets.
When the server and client are in the same machine, the code works fine.
But now I am trying to port forward my local server with ngrok, to chat with remote clients.
When the client wants to connect he would have to give the server url. If I am giving my localhost url, client connects to the socket server and everything works fine.
But whenever I am giving the ngrok's tcp tunnel url, it doesn't works and throws the error below
Traceback (most recent call last):
File "/storage/emulated/0/Sun/Python/cmd-chat/user.py", line 5, in <module>
client.connect((serverUrl, 5000)) #connecting client to server
socket.gaierror: [Errno 7] No address associated with hostname
The url I am giving as input is,
tcp://x.tcp.ngrok.io:17xxx
Hey I think I got where you are going wrong
# Your Server Url should be
serverUrl = hostAddress = "x.tcp.ngrok.io"
# The Port in which we want to connect to the server Should be
port = 17234 # The number given in the end of URL link

TCP Socket not connecting [WinError 10060] - Python

I'm making a chat app using sockets in python, but when I try to connect from a different computer then it says:
C:\Users\James\OneDrive\Documents\Python\Projects\Gui Chat\client.pyw
[WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
This is the server code for the socket:
host = socket.gethostbyname(hostname)
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
print(f"IP: {server.getsockname()[0]}\nPORT: {server.getsockname()[1]}")
server.listen()
I also have a while True loop accepting all requests:
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
On the client end this is the socket code:
IP = simpledialog.askstring("IP", "Enter IP address", parent=root) # "192.168.1.252" # input("Enter IP: ")
nickname = simpledialog.askstring("Nickname", "Choose a nickname", parent=root)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((IP, 55555))
except Exception as e:
print(e)
The programme asks for the IP address each time, and when I put in the correct IP for the server computer, it comes up with the error above. It works if I try to connect from the same computer, and they are both on the same network. It was working recently, and now it has just stopped working.
UPDATE:
I have set the server ip to 0.0.0.0, I have set up a port forwarding rule, I have checked the firewall and allowed incoming and outgoing connections, and I have run nmap with these results:
Code issues
First try binding server on localhost or 127.0.0.1.
FireWall/Ports issues
Check if your computer's default computer/antivurus
firewall (where server is hosted) allow connections
on your port 55555.
And if computer with client is outside your home network
point to router public IP address and make sure you have
port forwarding setup on router.
Address issues
Are you sure that IP you are writing in client is correct.
Go to your computer with server and check that IP.
Windows:
Go to cmd or Power Shell and type ipconfig, then find
section IPv4 Address and look that address you habe there.
Linux / MacOS
Go to your terminal and type ifconfig -a, and
it should be somewhere there, but I don't have those systems,
so I can't test it for you. If it does't work try to search how to
find that out.

How I can connect to another computer using a socket?

I try this code:
server:
import socket
s=socket.socket()
ip='localhost'
port=9999
s.bind((ip,port))
s.listen()
print("wait for client...")
c,addr=s.accept()
print("client added!")
while True:
msg=input("your masage:>>>")
c.send(msg.encode())
print(c.recv(1000000).decode())
client:
import socket
s=socket.socket()
ip='localhost'
port=9999
s.connect((ip,port))
print("connected")
while True:
print(s.recv(1000000).decode())
msg=input("your masage:>>>")
s.send(msg.encode())
and I get this error in the client:
Traceback (most recent call last):
File "F:\chat room\client\chat room-client.py", line 8, in <module>
s.connect((ip,port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
I try this on 2 computers and I was getting error but when I try this on 1 computer I don't get any error and the program work.
(please write code for answer)
You're pointing to localhost in both server and client sides. Assuming you are in a local network, you should first expose you server in '0.0.0.0' IP, so it can be seen externally to the host machine. Then, you need to know the local ip address of the server machine within the local network, and to use it as IP in the client side.
server:
import socket
s=socket.socket()
ip='0.0.0.0'
...
client:
import socket
s=socket.socket()
ip='YOUR-SERVER-MACHINE-LAN-IP' # You can obtain this IP with ipconfig (windows) or ifconfig (linux), usually like 192.168.x.x
...

"Connection Refused" running a server externally , although working locally

Trying to get into sockets and networking.
I wrote some simple server and client scripts and ran them,
which was working when connected locally and client-server communicated just fine, yet when my client script tries to connect to my_external_ip:open_port it gets a "Connection Refused" [WinError 10061]
I've opened a port (5234 in this case) and checked it using those port-scanning sites, what the server seems to react to and even accept connections.
Yet when I run my client script, it throws an exception, and the server doesn't seem to respond or even be aware of the connection attempt.
I've shut down my firewall temporarily and made sure I'm listening on 0.0.0.0:5234 (which to my understanding should be what I'm doing).
Am I missing something? doesn't make sense to me that the script runs locally, the server takes incoming external connections, yet this doesn't work.
Maybe the problem is that the client's outbound connection attempt is somehow blocked?
I cleaned up some unrelated code, but that's about it:
SERVER:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "" #Also tried socket.gethostname() and 0.0.0.0
port = 5234
s.bind((server,port))
s.listen()
connection, address = s.accept()
CLIENT:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = my_public_ip
self.port = 5234
self.client.connect((self.server,self.port)

Categories