【问题标题】:Connecting 2 devices on different networks using Python Sockets使用 Python 套接字连接不同网络上的 2 个设备
【发布时间】:2021-10-13 10:29:25
【问题描述】:

因此,如果有一个客户端和服务器具有各自的动态 IPv4 地址,并且两者都通过 2 个单独的路由器连接到互联网,我如何让客户端和服务器使用它们的动态 IPv4 地址和Python 3 中路由器的静态 IPv4 地址。

总的来说,我对网络很陌生,所以如果有其他标准方法可以做到这一点,请在下面提出更好的方法。

我目前有这段代码用于客户端和服务器端。

客户:

import socket
import tqdm
import os

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096 # send 4096 bytes each time step

# the ip address or hostname of the server, the receiver
host = "192.168.1.21"
# the port, let's use 5001
port = 20
# the name of file we want to send, make sure it exists
filename = ""
# get the file size
filesize = os.path.getsize(filename)

# create the client socket
s = socket.socket()

print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")

# send the filename and filesize
s.send(f"{filename}{SEPARATOR}{filesize}".encode())

# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
    while True:
        # read the bytes from the file
        bytes_read = f.read(BUFFER_SIZE)
        if not bytes_read:
            # file transmitting is done
            break
        # we use sendall to assure transimission in 
        # busy networks
        s.sendall(bytes_read)
        # update the progress bar
        progress.update(len(bytes_read))
# close the socket
s.close()

服务器:

import socket
import tqdm
import os
from pathlib import Path
# device's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5001
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

# create the server socket
# TCP socket
s = socket.socket()

# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))

# enabling our server to accept connections
# 5 here is the number of unaccepted connections that
# the system will allow before refusing new connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

# accept connection if there is any
client_socket, address = s.accept()
# if below code is executed, that means the sender is connected
print(f"[+] {address} is connected.")

# receive the file infos
# receive using client socket, not server socket
received = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
# remove absolute path if there is
filename = os.path.basename(filename)
# convert to integer
filesize = int(filesize)

# start receiving the file from the socket
# and writing to the file stream
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
home = str(Path.home())
with open(f"{home}/Downloads/{filename}", "wb") as f:
   while True:
       # read 1024 bytes from the socket (receive)
       bytes_read = client_socket.recv(BUFFER_SIZE)
       if not bytes_read:
           # nothing is received
           # file transmitting is done
           break
       # write to the file the bytes we just received
       f.write(bytes_read)
       # update the progress bar
       progress.update(len(bytes_read))

# close the client socket
client_socket.close()
# close the server socket
s.close()

注意:上面的客户端和服务端代码不是我写的。它是从另一个网站复制的,并稍作修改。

网站链接:https://www.thepythoncode.com/article/send-receive-files-using-sockets-python

【问题讨论】:

    标签: python sockets ipv4


    【解决方案1】:

    客户端在不同网络时将无法直接连接到服务器。

    服务器端的路由器必须配置为启用端口转发从路由器的 WAN IP/端口到服务器的 LAN IP/端口的入站流量。然后,服务器可以在其 LAN IP/端口上侦听连接,客户端可以连接到服务器路由器的 WAN IP/端口。

    必须在路由器的配置中处理端口转发。通常,这是由管理员手动完成的。但是,如果路由器支持(并已启用)UPnP,则服务器可以使用Internet Gateway Device protocol 从自己的代码动态设置端口转发。某些平台提供了为您实现该协议的 API(例如,Microsoft 的 NATUPNPLib 和 Windows 上的防火墙 API)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-09
      • 2019-08-12
      • 1970-01-01
      • 2020-07-15
      • 2022-11-06
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      相关资源
      最近更新 更多