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
...
Related
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.
I'm experimenting with socket server-client communication using python 3 socket module. Just to test if an eventual connection can be made, I've tried to program the simplest scenario possible. Thus the server code has the only purpose to print new connections; its code is:
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("0.0.0.0", 30000))
while True:
server.listen()
print("listening...")
conn, addr = server.accept()
print(f"{addr} connected")
while the client only tries to connect to the server using the public IPv4 address of my computer:
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Trying to connect...")
client.connect(("99.99.99.99", 30000))
client.close()
When I try to run the server and then the client nothing happens: the server just waits for conections, while the client displays nothing. After a while on the client side it is displayed the socket timeout error. I've tried to establish the connection even running the server and the client on the same computer, I've tried changing the ip of the server to "localhost" or "127.0.0.1", but nothing happens. Have you got any ideas on how this issue can be solved?
P.S. Thank you in advance for eventual answers and excuse my poor English, I'm still practising it!
I've been trying to implement a server-client connection, here is my code-
Server.py
import socket
server = socket.socket()
server.bind(('', 2112))
server.listen(5)
print('Server created with port 2112')
server.accept()
print('Connected')
Client.py
import socket
##Public_IP is the Public IP address of my router
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((Public_IP, 2112))
Both Server.py and Client.py are running on my computer(server). It works just fine when I replace Public_IP with '192.168.0.143', but when I use Public_IP, it gives the following error-
TimeoutError: [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
Is it because I'm running both Server.py and Client.py on the same computer? Please let me know what I'm doing wrong.
Setting up port forwarding -
Public IP
Port forwarding
Private IP address of server
I followed this tutorial for setting up port forwarding.
I also tried replacing the empty string in Server.py with my private IP address-
server.bind(('192.168.0.143', 2112))
Edit: I have tried-
Running Client.py externally (on a different LAN) with firewall down on both the ends, but didn't make any difference (it gave a timeout error).
Running Client.py on the same LAN with firewall down, that seemed to work fine.
Running the Client.py on the same device also worked fine with the firewall down.
Im using python socket to connect two computers,
it completely works when both systems are connected to one mobile hotspots or LAN,
But when i use two diffrent hotspots or try to connect to my friend's PC, it stops working and client cant find server.
(I find my IP using "ipconfig" command on cmd from "Wireless LAN adapter Wi-Fi: IPV4 Adress")
here are my codes for checking the connection:
#SERVER
import socket
s = socket.socket()
IP, port= MY IP, 8002
s.bind((IP,port))
while 1:
s.listen(1)
a,b=s.accept()
print(a,b)
print("client tried to connect")
#Client
import socket
s=socket.socket()
IP,port=SERVERS IP, 8002
s.connect((IP,port))
Can you guys help me please?
I've looked at many similar questions yet I can't figure out why connections are never established, they simply timeout. I've seen some questions where it's suggested a firewall (windows firewall) issue could be blocking me but I'm not so sure, I've tried disabling the firewall on both machines but the problem persists. There are also python rules which allows incoming and outgoing connections on both machines.
I've checked my router settings but I can't find anything there to suggest port forwarding is disabled etc.
I keep one of my devices on my home network and the other on my mobile data hotspot to simulate devices on separate networks. I've swapped around these devices.
I've used wireshark to inspect packets, I can see packets leaving on either network but never being received.
client.py
import socket
HOST, PORT = SERVERS-EXTERNAL-IP, 65000 #Tried a variety of ports
data = "Hello very cool message"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
print(f"Sent: {data}")
server.py
import socket
PORT = 65000
HOST = socket.gethostname() #Tried other things like '', ''localhost' etc
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(5)
print("Listening")
c, addr = sock.accept()
print("Accepted")
data = c.recv(1024)
sock.close()
client.py result:
Traceback (most recent call last):
File "client.py", line 15, in <module>
sock.connect((HOST, PORT))
TimeoutError: [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
server.py result:
Listening
Any suggestions as to why I'm facing this issue?
Ok I managed to get it working. Port forwarding was NOT setup, contrary to what I believed before.
To resolve this I created a static local IP address for my server, and a port forward rule in my router settings to direct a specific port to the static IP for the server. The following site was quite useful:
https://portforward.com
Also thanks to #SteffenUllrich for directing me in the right way.