Python3 NAT穿透

6

我知道这个话题不是新鲜事物。虽然有各种各样的信息,但健壮的解决方案没有被呈现出来(至少我没有找到)。我有一个用python3编写的P2P守护程序,将两个客户端连接到NAT后,通过TCP连接是最后一个问题。关于这个话题我的参考资料:

https://bford.info/pub/net/p2pnat/

如何在让两个客户端连接到一个会议点服务器之后,使它们直接相互连接?

TCP打洞问题

我到目前为止所做的:

nat_hole

服务器:

#!/usr/bin/env python3

import threading
import socket

MY_AS_SERVER_PORT = 9001

TIMEOUT = 120.0
BUFFER_SIZE = 4096

def get_my_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return bytes(IP, encoding='utf-8')

def wait_for_msg(new_connection, client_address):
    while True:
        try:
            packet = new_connection.recv(BUFFER_SIZE)
            if packet:
                msg_from_client = packet.decode('utf-8')
                client_connected_from_ip = client_address[0]
                client_connected_from_port = client_address[1]

                print("We have a client. Client advertised his local IP as:", msg_from_client)
                print(f"Although, our connection is from: [{client_connected_from_ip}]:{client_connected_from_port}")

                msg_back = bytes("SERVER registered your data. Your local IP is: " + str(msg_from_client) + " You are connecting to the server FROM: " + str(client_connected_from_ip) + ":" + str(client_connected_from_port), encoding='utf-8')
                new_connection.sendall(msg_back)
                break

        except ConnectionResetError:
            break

        except OSError:
            break

def server():
    sock = socket.socket()

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

    sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_SERVER_PORT))
    sock.listen(8)
    sock.settimeout(TIMEOUT)
    while True:
        try:
            new_connection, client_address = sock.accept()

            if new_connection:
                threading.Thread(target=wait_for_msg, args=(new_connection,client_address,)).start()
#               print("connected!")
#               print("")
#               print(new_connection)
#               print("")
#               print(client_address)
                msg = bytes("Greetings! This message came from SERVER as message back!", encoding='utf-8')
                new_connection.sendall(msg)
        except socket.timeout:
            pass


if __name__ == '__main__':
    server()

客户:

#!/usr/bin/python3

import sys
import socket
import time
import threading

SERVER_IP = '1.2.3.4'
SERVER_PORT = 9001
# We don't want to establish a connection with a static port. Let the OS pick a random empty one.
#MY_AS_CLIENT_PORT = 8510

TIMEOUT = 3
BUFFER_SIZE = 4096

def get_my_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except Exception:
        IP = '127.0.0.1'
    finally:
        s.close()
    return bytes(IP, encoding='utf-8')

def constantly_try_to_connect(sock):
    while True:
        try:
            sock.connect((SERVER_IP, SERVER_PORT))
        except ConnectionRefusedError:
            print(f"Can't connect to the SERVER IP [{SERVER_IP}]:{SERVER_PORT} - does the server alive? Sleeping for a while...")
            time.sleep(1)
        except OSError:
            #print("Already connected to the server. Kill current session to reconnect...")
            pass

def client():
    sock = socket.socket()

    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)

    #sock.bind((get_my_local_ip().decode('utf-8'), MY_AS_CLIENT_PORT))
    sock.settimeout(TIMEOUT)

    threading.Thread(target=constantly_try_to_connect, args=(sock,)).start()

    while True:
        try:
            packet = sock.recv(BUFFER_SIZE)

            if packet:
                print(packet)
                sock.sendall(get_my_local_ip())

        except OSError:
            pass

if __name__ == '__main__':
    client()

现在的代码结果如下:

./tcphole_server.py 
We have a client. Client advertised his local IP as: 10.10.10.50
Although, our connection is from: [89.22.11.50]:32928
We have a client. Client advertised his local IP as: 192.168.1.20
Although, our connection is from: [78.88.77.66]:51928

./tcphole_client1.py              
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 192.168.1.20 You are connecting to the server FROM: 89.22.11.50:32928'

./tcphole_client2.py             
b'Greetings! This message came from SERVER as message back!'
b'SERVER registered your data. Your local IP is: 10.10.10.50 You are connecting to the server FROM: 78.88.77.66:51928'

您可以看到,服务器具有连接两个客户端所需的所有信息。我们可以通过当前的服务器-客户端连接单独发送关于另一对等方的详细信息。

现在我头脑中还有两个问题:

  1. 假设服务器为每个对等方发送有关客户端1和客户端2的信息。现在客户端开始连接,如[89.22.11.50]:32928 <> [78.88.77.66]:51928,服务器是否应关闭与客户端的当前连接?

  2. 客户端路由器会如何表现?我想它期望相同的外部服务器SRC IP [1.2.3.4],而不是获得其中一个客户端的EXT IP,例如[89.22.11.50]或[78.88.77.66]?

这比我想象的要复杂。任何帮助推动事情向前发展的帮助都将不胜感激。希望这也能帮助其他开发人员/运维人员。


如果您想发布自己的答案,那是可以的,但不要放在问题里。 - DisappointedByUnaccountableMod
1个回答

4

终于找到了预期的行为!这里不想贴太多代码,但我希望通过这篇文章,您能够理解如何实现其基础。最好在每个客户端文件夹中都有一个单独的文件,例如 ./tcphole_client1.py./tcphole_client2.py。在我们启动与服务器的会话后,需要快速进行连接。例如:

./tcphole_client_connector1.py 32928 51928

./tcphole_client_connector2.py 51928 32928

还记得吗?我们需要连接到与服务器(initiated with SERVER)相同的端口。

[89.22.11.50]:32928 <> [78.88.77.66]:51928

第一个端口用于绑定套接字(OUR)。使用第二个端口,我们尝试连接到客户端(CLIENT)。另一个客户端执行相同的过程,只是它会绑定到自己的端口,并连接到你绑定的端口。如果路由器仍然有一个活动连接-成功。


太好了!我正好找到了这个解决方案,但是如果我想在我的服务器和更多客户端之间建立一个隧道,所有连接的端口都是61480,该怎么办?我希望所有客户端和服务器都通过该端口进行通信。非常感谢! - Manuel Santi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接