Issue
I am a beginner in socket communication and I wanted to test this code.
I wrote the same code but changed the host in the server to s.gethostname() when both the client and server were on my laptop and worked normally.
server: Laptop
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ''
port = 62402
s.bind((host,port))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"connection from {address} has been established!")
clientsocket.send(bytes("Welcome to the server!","utf-8"))
client: raspberry pi
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 62402
s.connect((host,port))
msg = s.recv(1024)
print(msg.decode('utf-8')
Error
Traceback(most recent call last):
File "/home/pi/Desktop/testting/client.py", line 6, in <module>
s.connect((host,port))
ConnectionRefusedError: [Error 111] Connection refused
Solution
Connection refused tells me that [the target] is not accepting the connection. I don’t think ´socket.gethostname()´ can possibly return the laptop’s hostname in its current form. ´print()´ what it returns - I’d bet it’s the local machine’s hostname (the one creating the connection).
Once you know where you’re connecting to, Things that could go wrong:
- Is your target listening for a connection on port 62402?
- Will its firewall allow such traffic in?
Answered By - Adam Smooch