Python套接字服务器:拒绝来自地址的连接 [英] Python socket server : Reject connection from address

查看:96
本文介绍了Python套接字服务器:拒绝来自地址的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 套接字服务器,它侦听一个端口,并使用以下方法接受所有传入连接:

I have a python socket server that listens on a port, and accepts all incoming connections using:

(conn, address) = socket.accept()

但是,我希望只接受来自特定 IP 地址的连接.

However, I wish to accept connections only from certain ip address.

目前,如果地址未注册,我会关闭连接以完成此操作.

Currently, I close the connection if the address isn't registered, to accomplish this.

但是有没有更好的方法来做到这一点,直接拒绝来自未注册地址的连接,而不是接受连接然后关闭它们?

But is there a better way to do this, by directly rejecting connections from unregistered addresses, instead of accepting connections and then closing them?

推荐答案

无法向来自某些 IP 地址的客户端指示连接被拒绝,并且无法与来自其他 IP 地址的客户端建立连接.这不是 Python 限制,而是较低级别的 BSD 套接字层限制.你连 C 都做不到.

It's not possible to indicate Connection refused to clients from some IP addresses, and to establish the connection to clients from other IP addresses. This is not a Python limitation, but a lower-level, BSD socket layer limitation. You can't do it even from C.

通常您可以在 Python 中执行的最接近的行为是在连接被接受后迅速关闭连接:

The closest behavior in general you can do in Python is closing the connection quickly after it has been accepted:

sock, addr = server_socket.accept()
if addr[0] != '12.34.56.78':
  sock.close()
  return
...

然后客户端会看到连接被接受,不久之后客户端会在读取它时看到 EOF,并且无法写入.

Then the client would see the connection being accepted, and very shortly after that the client would see EOF when reading from it, and it wouldn't be able to write to it.

但是,可以在绑定时通过接口(即网卡)进行限制,方法是使用以下之一:

However it's possible to limit by interface (i.e. network card) at bind time, by using one of:

server_socket.bind(('', 65432))  # Bind on any interface.
server_socket.bind(('127.0.0.1', 65432))  # Bind on loopback (localhost clients only).
server_socket.bind(('34.56.78.91', 65432))

所以在 127.0.0.1 版本中,telnet 127.0.0.1 65432(作为客户端)可以工作,但 telnet myhostname 65432 会yield 连接被拒绝(并且 server_socket.accept() 调用不会获得此连接).

So in the 127.0.0.1 version, telnet 127.0.0.1 65432 (as a client) would work, but telnet myhostname 65432 would yield Connection refused (and the server_socket.accept() call won't get this connection).

这篇关于Python套接字服务器:拒绝来自地址的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆