python中的端口转发以允许套接字连接 [英] Port forwarding in python to allow socket connections

查看:58
本文介绍了python中的端口转发以允许套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用套接字启动服务器,并希望允许客户端连接到它.

I start a server using sockets and want to allow clients to connect to it.

self.sock.bind(('0.0.0.0',0)) # 0.0.0.0 will allow all connections and port 0 -> os chooses a open port.
stroke_port=self.sock.getsockname()[1]
self.sock.listen(75)
self.open_port_popup(stroke_port)

现在,对于要连接的其他客户端,我手动进行了端口转发,并且工作正常.

Now, for other clients to connect I have port forward it manually and it works fine.

我想以自动化方式执行此操作.-> 我试试 upnp.

I want to do this in automated fashion. -> I try upnp.

import miniupnpc

def open_port(port_no):
    '''this function opens a port using upnp'''
    upnp = miniupnpc.UPnP()

    upnp.discoverdelay = 10
    upnp.discover()

    upnp.selectigd()

    # addportmapping(external-port, protocol, internal-host, internal-port, description, remote-host)
    result=upnp.addportmapping(port_no, 'TCP', upnp.lanaddr, port_no, 'testing', '')
    return result

它会打开一个如下图所示的端口.但是第一张图片中显示的端口转发列表是空的.它不起作用,客户端无法连接.我怎样才能解决这个问题?我错过了什么?

It opens a port shown in the image below. But the port-forwarding list shown in the first image is empty. It doesn't work and clients can't connect. How can I fix this? What am I missing?

推荐答案

我认为您使用 upnp.lanaddr 作为内部主机地址犯了一个错误.upnp.lanaddr 是你的路由器 upnp 设备的地址,你想使用你服务器的本地地址.

I think you made a mistake using upnp.lanaddr as internal-host address. upnp.lanaddr is the address of the upnp device which is your router, you want to use the local address of your server.

如果需要,请查看使用 Python 的 stdlib 查找本地 IP 地址 如果您想动态获取服务器本地 IP.

If needed take a look at Finding local IP addresses using Python's stdlib if you want to get your server local IP dynamically.

这篇关于python中的端口转发以允许套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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