简体   繁体   English

用python在不同局域网之间发送数据

[英]Send data between different LANs in python

I've been trying for two weeks to create a Python script that will communicate with itself even if run from different LANs.两周以来,我一直在尝试创建一个 Python 脚本,即使从不同的 LAN 运行,该脚本也能与自身进行通信。

But I can not perform the NAT traversal.但是我不能执行NAT穿越。 I've tried to check what's going wrong and at least the socket isn't timeout ing anymore but I can't receive the data.我试图检查出了什么问题,至少套接字不再timeout ,但我无法接收数据。

I think the issue might be that the NAT is mapping the send and receive to different port but don't know how to check that or fix it if it is really the issue.我认为问题可能是 NAT 将发送和接收映射到不同的端口,但不知道如何检查或修复它是否真的是问题。

Code:代码:

import socket
import time
from threading import Thread

PORT = 4206
peers = [''] # public ip adresses
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
LOCAL_HOST = ('127.0.0.1', PORT)


def main():
    print('P2P are set to PORT :', PORT)
    Thread(target=nat_traversal).start()


def recv():
    time.sleep(5)
    while True:
        print('response:', sock.recvfrom(4096))


def sec30():
    for i in range(0, 29):
        time.sleep(1)
        print(i, end=',')
    time.sleep(1)
    print('30')


def nat_traversal():
    Thread(target=recv).start()
    while True:
        t = Thread(target=sec30, args=())
        t.start()
        for peer in peers:
            if peer != '':
                try:
                    sock.sendto(b'Hey', (peer, PORT))
                except TimeoutError:
                    print('timeout')
        t.join()


if name == 'main':
    main()

Can you give me examples of a Python script that performs nat traversal and can send and receive messages?你能给我一个执行 nat 遍历并且可以发送和接收消息的 Python 脚本的例子吗?

Thanks in advance (:提前致谢 (:

NAT means that it can translate a IP outside to a IP inside, but many NAT types don't alow the IP from outside to start the conneciton. NAT 意味着它可以将外部 IP 转换为内部 IP,但许多 NAT 类型不允许来自外部的 IP 启动连接。 So your program may not work.所以你的程序可能无法运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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