pythonsocketsconnectiontimeout

Python socket can not connect on two separated machines


I used the socket library in Python, and made two simple projects which are server.py and client.py, then I executed them as server.exe and client.exe When I run both (server.exe and client.exe) on my computer, it works fine, but when I run them on two separate computers, the client can not connect to the server that runs on the other computer. Here is my code:

Server side:

import socket

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# use our ipv4 for making server on port 9000, and show it on the screen
ip = socket.gethostbyname(socket.gethostname())
server.bind((ip,9000))
server.listen(1)
print(f"The server ipv4 , give it to client to connect to the server -> {ip}")

print("Waiting for client ...")
client_socket = server.accept()[0]

client_socket.send(b"hello")

client_socket.close()
server.close()
print("Done !!")

Client side:

import socket

server_ip = input("Please enter server ipv4 here : ")

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((server_ip,9000))

# receive data from server (b"hello" which sent from the server)

Print(client.recv(5).decode('utf-8'))

client.close()
print("Done !!")

There are no more exceptions in these two codes but just one exception appears on the client side when I am trying to connect the client to the server which runs on another computer as I said above.

The exception on the client side says that the client socket attempted to connect to the server, but it could not connect to the server, and it said something about timeout connection. I searched a lot and watched lots of videos that make the same projects for testing sockets in python and it works for them, but not for me :( I allowed the client and server in firewall on two computers, also disabled the firewall, but it did not work at all, and the same exception appeared. I used netstat -a (cmd command) on the computer on which the server was running on it, and saw that the server socket was listening on port 9000.

Nothing seems to work, any help will be appreciated.


Solution

  • I think this is virtually impossible without an online host or any third party programs, if I say correctly, this because a main difference between network and internet, we use network for devices which connected to a same router, these devices can easily communicating together because they are in a local network, but we use internet for groups of devices (network groups) connection through different routers. This is what I understood after researches.(sorry if my explained wrongly) Are there any free host for testing projects (host for python which supports socket libraries) ?