-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcliente.py
More file actions
163 lines (124 loc) · 4.94 KB
/
cliente.py
File metadata and controls
163 lines (124 loc) · 4.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import socket
import os
import platform
import hashlib
NGROK_HOST = '0.tcp.sa.ngrok.io'
NGROK_PORT = 19034
SERVER_IP = ""
SERVER_PORT = NGROK_PORT
def calcular_hash(caminho):
sha256 = hashlib.sha256()
with open(caminho, "rb") as f:
while chunk := f.read(4096):
sha256.update(chunk)
return sha256.hexdigest()
def corrigir_caminho(caminho_original):
caminho = caminho_original.strip().strip('"').strip("'")
if os.path.exists(caminho):
return caminho
def send_file():
print("\n MODO ENVIAR")
print("\nPode arrastar o arquivo para cá, eu resolvo o caminho.")
raw_input = input("Caminho: ")
filename = corrigir_caminho(raw_input)
if not filename:
print("\n ERRO FATAL: Arquivo não encontrado.")
return
print(" Calculando Hash e lendo arquivo...")
file_hash = calcular_hash(filename)
filesize = os.path.getsize(filename)
name_only = os.path.basename(filename)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print(f"📡 Conectando em {SERVER_IP}:{SERVER_PORT}...")
client.connect((SERVER_IP, SERVER_PORT))
client.send(f"SEND|{name_only}|{filesize}|{file_hash}".encode())
response = client.recv(1024).decode()
if response.startswith("CODE:"):
code = response.split(":")[1]
print(f"\n✅ CÓDIGO GERADO: {code}")
print("⏳ Aguardando o receptor conectar... (Não feche esta janela)")
while True:
msg = client.recv(1024).decode()
if msg == "UPLOAD_NOW":
print(f"--> Iniciando transferência...")
with open(filename, 'rb') as f:
total_sent = 0
while total_sent < filesize:
data = f.read(4096)
if not data: break
client.send(data)
total_sent += len(data)
print(f"\n--> Sucesso! Transferência concluída.")
print("Conexão aberta, para mais transferências, caso deseje fechar, aperte Ctrl + C")
elif msg == "":
print("Conexão perdida.")
break
else:
print(f"Erro no servidor: {response}")
except KeyboardInterrupt:
print("\nCancelado pelo usuário.")
except Exception as e:
print(f"Erro de conexão: {e}")
finally:
client.close()
def receive_file():
print("\nMODO RECEBER")
code = input("\nDigite o código fornecido por quem envia: ").strip()
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print(f"📡 Conectando em {SERVER_IP}:{SERVER_PORT}...")
client.connect((SERVER_IP, SERVER_PORT))
client.send(f"RECV|{code}".encode())
server_msg = client.recv(1024).decode()
if server_msg.startswith("FILENM|"):
parts = server_msg.split("|")
filename = parts[1]
filesize = int(parts[2])
hash_recebido = parts[3]
output_name = f"baixado_{filename}"
print(f"\n📥 Recebendo arquivo: {filename}")
client.send("OK".encode())
received_total = 0
with open(output_name, 'wb') as f:
while received_total < filesize:
to_read = min(4096, filesize - received_total)
data = client.recv(to_read)
if not data: break
f.write(data)
received_total += len(data)
print(f"✅ Download concluído: {output_name}")
print("Verificando integridade")
hash_calculado = calcular_hash(output_name)
if hash_calculado == hash_recebido:
print("✅ SUCESSO! O arquivo é idêntico ao original.")
else:
print("❌ PERIGO: O hash não bate! O arquivo pode estar corrompido.")
elif server_msg.startswith("ERROR:"):
print(f"Erro do servidor: {server_msg}")
except Exception as e:
print(f"Erro: {e}")
finally:
client.close()
def main():
global SERVER_IP
print("=== P2P FILE TRANSFER (CLIENTE) ===")
try:
SERVER_IP = socket.gethostbyname(NGROK_HOST)
print(f"✅ Servidor Conectado")
except socket.gaierror:
print("❌ ERRO: Não foi possível encontrar o IP do Ngrok.")
print("Verifique se digitou o endereço correto no código.")
return
print("-----------------------------------")
print("1. Enviar Arquivo")
print("2. Receber Arquivo")
opcao = input("Opção: ")
if opcao == '1':
send_file()
elif opcao == '2':
receive_file()
else:
print("Opção inválida.")
if __name__ == "__main__":
main()