![](/img/trans.png)
[英]Python/socket: How to send a file to another computer which is on a different network?
[英]How can I send my file to another network?
我找不到將文件發送到另一個網絡的方法。 我有一個文件要發送到不在同一網絡上的另一台計算機。 現在我正在使用服務器和客戶端。 這是服務器端:(我使用 tqdm 生成一個顯示進度的小條)
import socket
import tqdm
import os
SERVER_HOST = "" #using public IP will generate an error, so I left it blank
SERVER_PORT = 5001
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
s = socket.socket()
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(10)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
print("Waiting for the client to connect... ")
client_socket, address = s.accept()
print(f"[+] {address} is connected.")
received = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
while True:
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
progress.update(len(bytes_read))
client_socket.close()
s.close()`
我試圖將我的公共 ip 設置為 SERVER_HOST,但它給了我一個錯誤:“請求的地址在其上下文中無效”。 但是我刪除了公共地址並在客戶端使用了我的 IPv4,這允許我在本地網絡中傳輸文件(但我希望它可以在任何地方工作)。 這是客戶端:
import tqdm
import os
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
s = socket.socket()
host = "192.168.0.17"
port = 5001
print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected to ", host)
filename = "data.txt"
filesize = os.path.getsize(filename)
print(f"{filesize}")
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
break
s.sendall(bytes_read)
progress.update(len(bytes_read))
s.close()
任何建議將不勝感激。 還有沒有更好的方法來傳輸我可以嘗試的文件?
答:我所要做的就是端口轉發,它工作了。 如果你有興趣,有很多關於這個主題的教程。 謝謝您的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.