Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening socket to outside computer with Python

I am using the following code to open a socket on my computer. When I go to my_ip:5000 on my computer the program responds. However, when I use another computer, nothing happens.

HOST = 'my_ip'                 # Symbolic name meaning the local host
PORT = 8000              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

I'm not sure if this is an issue with the firewall or not. When I start up the test server in django using manage.py runserver my_ip:8000 I am able to connect to the machine from a different computer. I'm not sure what is causing me not to be able to connect from another computer using the code above...

like image 469
Alexis Avatar asked Mar 25 '26 10:03

Alexis


1 Answers

By setting HOST to 'my_ip', you may listen to a private IP that only resolves to your computer for your computer. The best-known example is 127.0.0.1. Instead, pass an empty string (HOST='') to listen to any requests coming in at the specified port. Make sure to use the same port number, i.e. either 5000 or 8000, on both machines.

Also, check whether a firewall between the computers (or installed on one of them) prevents the connection.

To test whether your computer is reachable in principle, run python -m SimpleHTTPServer in a directory without private information on the server and try to reach the webserver started with that from the client.

like image 167
phihag Avatar answered Mar 26 '26 23:03

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!