Reputation:
I am new to socket library and server side programming. I made 2 scripts which runs perfectly on my machine i.e. server.py
and client.py
. But when i test it on two different computers it doesn't worked.
What i want is to make my
server.py
file connected toclient.py
, whereserver.py
will run on my machine and it will be connected toclient.py
on a separate machine at any location in the world.
I just know socket only. But if this problem can be solved by use of other library, then also it will be fine.
Here is my code:
server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
port = 12048
s.bind((host, port))
s.listen()
print("Server listening @ {}:{}".format(host, port))
while True:
c, addr = s.accept()
print("Got connection from", addr)
c.send(bytes("Thank you", "utf-8"))
client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # The IP printed by the server must be set here
port = 12048
s.connect((socket.gethostname(), port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
I don't know how it's possible but if it is then please answer this.
Also, i want to receive files from client.py
to my machine. Is it possible in socket or i have to import any other library?
Any help will be appreciated.
Upvotes: 1
Views: 2476
Reputation: 1136
In Client.py you're connecting the socket to socket.gethostname()
instead of the ip address of your server. Now, your client is trying to a server that should be running on the same ip as the client. Logically this will work when server and client run on the same ip, but when the client resides on another machine you need to connect to the correct ip address:
s.connect((host, port))
Also, make sure that port is actually open and not blocked by another program. This website helped me open port 7777 on two different laptops and run your edited code on them. You can do the same for port 12048.
I believe for a socket you have to open the TCP port but if that doesn't work you can make a new rule for the UDP port as well.
Upvotes: 2
Reputation: 1111
The reason the client will only connect to the server running on the same computer is because you are using s.connect((socket.gethostname(), port))
instead of s.connect((host, port))
. Your host
IP variable is never being used. This error means that the client will be trying to connect to its own hostname, which would be itself, and so that is why it only works on one single computer.
You should modify client.py
like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.1.162' # Make sure this is set to the IP of the server
port = 12048
s.connect((host, port))
msg = s.recv(1024)
print(msg.decode("utf-8"))
Now you will be able to connect to a server running on a different computer.
Upvotes: 2