def __init__(self): self.peer_list = [] tracker_sock = create_socket() tracker_sock.bind(('', TRACKER_PORT)) print("Tracker port:", TRACKER_PORT) tracker_sock.listen(1) reports_sock = create_socket() reports_sock.bind(('', REPORTS_SOCK_PORT)) print("Reports port:", REPORTS_SOCK_PORT) reports_sock.listen(1) self.peer_socks = {} self.reports = {} self.tracker_sock = tracker_sock self.reports_sock = reports_sock self.tracking_thread = threading.Thread(target=self.start_tracking) self.tracking_thread.start() self.reports_thread = threading.Thread(target=self.listen_reports, args=[self]) self.reports_thread.start()
def __init__(self, host=localhost, port=default_port): self.server_socket = create_socket((host, port)) self.connections = [self.server_socket] self.u = Utils(self.connections, self.server_socket) self.usr_database = self.u.load_usr_pass() self.login_count = {} print "PyTalk server started at %s on port %s" % (localhost, str(port))
def send_getblocks_handler(self, conexion): client_socket = utils.create_socket(conexion) command = self.metadata(GETBLOCKS_COMMAND) client_socket.send(command) self.__update_events(f'-> {GETBLOCKS_COMMAND.strip(".").upper()} height: {self.current_height}') client_socket.send(self.current_height.to_bytes(4, 'little')) # Receive command command_metadata = client_socket.recv(31) command = command_metadata[:12].decode('utf-8') if command != INV_COMMAND: # Did not receive inventory self.__update_events('Did not receive inventory') client_socket.close() return self.__update_events(f'<- {INV_COMMAND.strip(".").upper()}') # Receive inv metadata inv_metadata = client_socket.recv(8) heigth, number_blocks_hashes = utils.decode_inv_metadata(inv_metadata) self.__update_events(f'Blockchain out of sync. Node height {self.current_height} and received heigth {heigth}. Receiving {number_blocks_hashes} blocks') # Receive inv blocks hashes block_hashes = [] for _ in range(number_blocks_hashes): block_hash = client_socket.recv(64).decode('utf-8') block_hashes.append(block_hash) client_socket.close() for block_hash in block_hashes: self.send_getdata_handler(conexion, block_hash)
def send_tx_handler(self, conexion, tx): client_socket = utils.create_socket(conexion) # Send tx command command = self.metadata(TX_COMMAND) client_socket.send(command) self.__update_events(f'-> {TX_COMMAND.strip(".").upper()} {{ id: {tx.txID} }}') payload = tx.serialize() client_socket.send(payload) client_socket.close()
def send(self, port, msg): sock = create_socket() sock.connect(('127.0.0.1', int(port))) msg = self.attach_headers(msg) msg_len = str(len(msg)).zfill(5) sock.send(msg_len.encode('utf-8')) sock.send(msg.encode('utf-8'))
def __init__(self, port): self.port = port self.total = 0 self.m_recv = {} self.n_recv = {} self.is_alive = True sock = create_socket() sock.connect(('127.0.0.1', TRACKER_PORT)) num_peer_ports = int(sock.recv(5).decode("utf-8")) if num_peer_ports > 1: peer_ports_str = sock.recv(num_peer_ports).decode('utf-8') peer_ports = peer_ports_str.split(",") print("Received peer list", peer_ports) # for peer_port in peer_ports: # if peer_port: # self.connect_to(int(peer_port)) server_sock = create_socket() print("Creating peer on port: ", port) server_sock.bind(('', port)) server_sock.listen(1) self.server_sock = server_sock sock.send(str(port).encode("utf-8")) self.incoming_connection_thread = threading.Thread( target=self.handle_incoming_connection) self.incoming_connection_thread.start()
def handle_incoming_connection(self): while True: try: incoming_peer_sock, incoming_peer_addr = self.server_sock.accept( ) msg_len = incoming_peer_sock.recv(5).decode('utf-8') if msg_len == 'quitt': print("Quitting.") break msg_len = int(msg_len) msg = incoming_peer_sock.recv(msg_len).decode('utf-8') sender_port, msg = self.extract_msg(msg) print("Recevied:", msg, "from", sender_port) self.total += 1 if sender_port in self.n_recv: self.m_recv[sender_port] += self.is_malicious(msg) else: self.m_recv[sender_port] = self.is_malicious(msg) if sender_port in self.n_recv: self.n_recv[sender_port] += 1 else: self.n_recv[sender_port] = 1 w1 = self.n_recv[sender_port] / self.total w2 = self.m_recv[sender_port] / self.n_recv[sender_port] belief = 0.3 * w1 + 0.7 * w2 if belief >= 0.8: print("Reporting", sender_port, "to tracker for malicious activity.") sock = create_socket() sock.connect(('127.0.0.1', REPORTS_SOCK_PORT)) sock.send(str(sender_port).zfill(5).encode('utf-8')) incoming_peer_sock.close() except KeyboardInterrupt: break os._exit(1)
def send_getdata_handler(self, conexion, block_hash): command = self.metadata(GETDATA_COMMAND) # Send getdata command client_socket = utils.create_socket(conexion) client_socket.send(command) self.__update_events(f'-> {GETDATA_COMMAND.strip(".").upper()} for block {block_hash}') payload = block_hash.encode('utf-8') client_socket.send(payload) # Check if Receive block command command_metadata = client_socket.recv(31) command = command_metadata[:12].decode('utf-8') if command != BLOCK_COMMAND: client_socket.close() return self.__update_events(f'<- {BLOCK_COMMAND.strip(".").upper()}') self.receive_block_handler(client_socket)
def send_conexion_handler(self, conexion): client_socket = utils.create_socket(conexion) # Send version message self.send_version_handler(client_socket) # Receive verack command_metadata = client_socket.recv(31) command = command_metadata[:12].decode('utf-8') if command != VERACK_COMMAND: # Message Received is not verack self.__update_events('Did not receive verack') client_socket.close() return # If verack Received, add conexion to peers self.peers.append(conexion) self.__update_events(f'<- {VERACK_COMMAND.strip(".").upper()} node {conexion} added to peers') # Close client socket client_socket.close()
def listen_reports(self, parent): reports = parent.reports while True: try: peer_sock, peer_addr = self.reports_sock.accept() reported_port = int(peer_sock.recv(5).decode('utf-8')) if reported_port in reports: reports[reported_port] += 1 else: reports[reported_port] = 1 if reports[reported_port] >= 2: self.peer_list.remove(reported_port) sock = create_socket() sock.connect(('127.0.0.1', reported_port)) sock.send('quitt'.encode('utf-8')) print("Removed", reported_port, "from the network due to malicious detection.") peer_sock.close() except KeyboardInterrupt: break
def connect_to(self, port): sock = create_socket() sock.connect(('127.0.0.1', port))
#!/usr/bin/env python import os, sys, socket, select, time from ping_thread import * from utils import get_timer, create_socket, print_statistics lock = threading.Lock() if __name__ == '__main__': default_timer = get_timer() ping_socket = create_socket() if(ping_socket != None): threads = [] for host in sys.argv[1:]: event = threading.Event() thread = PingThread(host, event, ping_socket, lock) threads.append((id(thread) & 0xFFFF, event, thread)) thread.setDaemon(True) thread.start() while(any(thread[2].isAlive() == True for thread in threads)): ready = select.select([ping_socket], [], [], 1) if not ready[0]: continue try: with lock: recPacket, addr = ping_socket.recvfrom(2048) except socket.error: print("Can't receive")
# implementing 3-tier structure: Hall --> Room --> Clients; # 14-Jun-2013 import select, socket, sys, pdb from utils import Hall, Room, Player import utils READ_BUFFER = 4096 host = sys.argv[1] if len(sys.argv) >= 2 else '141.244.85.187 ' listen_sock = utils.create_socket((host, utils.PORT)) hall = Hall() connection_list = [] connection_list.append(listen_sock) while True: # Player.fileno() read_players, write_players, error_sockets = select.select( connection_list, [], []) for player in read_players: if player is listen_sock: # new connection, player is a socket new_socket, add = player.accept() new_player = Player(new_socket) connection_list.append(new_player) hall.welcome_new(new_player) else: # new message msg = player.socket.recv(READ_BUFFER) if msg: msg = msg.decode().lower()
def new_block_handler(self, conexion, block_hash): # Create socket to send block to conexion client_socket = utils.create_socket(conexion) self.send_block_handler(client_socket, block_hash)
import socket # We connect to a (host,port) tuple import utils import time import binascii ADDRESS_A = ("cc5312.xor.cl", 5312) ADDRESS_B = ("cc5312.xor.cl", 5313) sock_A_input, sock_A_output= utils.create_socket(ADDRESS_A) sock_B_input, sock_B_output = utils.create_socket(ADDRESS_B) sock_C_input, sock_C_output= utils.create_socket(ADDRESS_A) sock_D_input, sock_D_output = utils.create_socket(ADDRESS_B) def senAResendB(message): """ Enía message a A, y respues de A la envía a B. Retorna Respuesta de B. """ resp_A = utils.send_message(sock_A_input, sock_A_output, message) resp_B = utils.send_message(sock_B_input, sock_B_output, resp_A) # if not (resp_B == message): # print(resp_B) return resp_B, len(resp_A) def senAResendB2(message): """ Enía message a A, y respues de A la envía a B. Retorna Respuesta de B. """
import socket # We connect to a (host,port) tuple import utils CONNECTION_ADDR = ("cc5312.xor.cl", 5312) if __name__ == "__main__": sock_input, sock_output = utils.create_socket(CONNECTION_ADDR) while True: try: # Read a message from standard input response = input("send a message: ") # You need to use encode() method to send a string as bytes. print("[Client] \"{}\"".format(response)) resp = utils.send_message(sock_input, sock_output, response) print("[Server] \"{}\"".format(resp)) # Wait for a response and disconnect. except Exception as e: print(e) print("Closing...") input.close() break
import select import socket import sys import pdb from utils import Hall, Room, Player import utils server = "localhost" port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_sock = utils.create_socket((server, port)) try: s.bind((server, port)) except socket.error as e: str(e) s.listen(2) print("Waiting for a connection, Server Started") hall = Hall() connection_list = [] connection_list.append(listen_sock) while True:
import socket from pprint import pprint # We connect to a (host,port) tuple import utils import time ADDRESS_A = ("cc5312.xor.cl", 5312) ADDRESS_B = ("cc5312.xor.cl", 5313) sock_A = utils.create_socket(ADDRESS_A) sock_B = utils.create_socket(ADDRESS_B) def senAResendB(message): """ Enía message a A, y respues de A la envía a B. Retorna Respuesta de B. """ resp_A = utils.send_message(sock_A, message) resp_B = utils.send_message(sock_B, resp_A) # if not (resp_B == message): # print(resp_B) return resp_B, len(resp_A) def calcBlockSize(): """ Retorna el número en bytes del tamaño del bloque. Envía mensajes cada vez más largos al servidor (aumentados en 8 bits) Y cuenta cada cuantos mensajes enviados, la respuesta del servidor es más larga. Es decir, cuantos bytes tuve que agregar para que la respuesta fuera más larga.