简体   繁体   中英

How to allow or deny remote connections in Python's SocketServer?

I'm creating an extremely simple Vega visualization viewer: it's a one file module that serves a base HTML page containing just the Vega graphic and an HTML5 EventSource of updates. The user (me) is working in a Python shell through ssh, creates an object representing the viewer, which prints its IP and port for the user to paste into their (my) web browser. This HTTP server doesn't serve files or take input from clients, so I don't see any security concerns.

The part I'm unsure of is how to set (host, port) such that my web browser can find the HTTP server running in the remote Python. I've been experimenting all afternoon, and I don't know if I'm misunderstanding what's supposed to happen or if the servers I use have changed their access policies.

Here's a minimal example:

import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer((host, port), Handler)
print(httpd.server_address)
httpd.serve_forever()

If I'm running this locally and want to ensure that outside viewers cannot access it, do I set host to "127.0.0.1" because that means a client would have to access it as 127.0.0.1, which can only happen locally? In this case, port can be 0 to get any open port.

If I'm running this remotely want to to ensure that outside viewers can access it, do I set host to "" or "0.0.0.0" because that means that a client can access it as any address that makes its way to the server? In this case, I might not be able to set port to 0 because many of those ports might be blocked, or is the OS smarter about this?

Basically, how is access control in Python's SocketServer supposed to work?

This is basic TCP. Nothing to do with Python.

If you listen at 127.0.0.1, only clients running in the same host can connect.

If you listen at 0.0.0.0, anybody can connect, firewalls permitting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM