diff --git a/main.py b/main.py index e15259e..3a91260 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,5 @@ +# https://git.krzak.org/N0VA/ESharePy/raw/branch/main/main.py + import sys import os import socket @@ -25,10 +27,35 @@ KEY_MAP = { 'p': (26, "POWER"), } +def get_broadcast_addresses(): + broadcasts = {'255.255.255.255'} + try: + with open('/proc/net/route') as f: + for line in f.readlines()[1:]: + fields = line.strip().split() + dest = fields[1] + mask = fields[7] + if dest == '00000000': + continue + d = int(dest, 16) + m = int(mask, 16) + b = (d & m) | (~m & 0xFFFFFFFF) + broadcasts.add(socket.inet_ntoa(struct.pack('IIIII", packet, 0, 0, 0, 0, len(magic), 0) packet[20:20 + len(magic)] = magic - try: - sock.sendto(packet, ("255.255.255.255", 48689)) - while True: + for bcast in get_broadcast_addresses(): + try: + sock.sendto(packet, (bcast, 48689)) + except Exception: + pass + + t_end = time.time() + timeout + found_devices = [] + + while time.time() < t_end: + try: data, addr = sock.recvfrom(1024) reply = data.decode("utf-8", errors="ignore") if reply.startswith("ECloudBox"): parts = reply.split(":") name = parts[1] if len(parts) > 1 else "Unknown" port = int(parts[2]) if len(parts) > 2 and parts[2].isdigit() else 8121 - print(f"Found TV: '{name}' at {addr[0]}:{port}") - return addr[0], port, name - except socket.timeout: - print("No TV responded to UDP broadcast.") - finally: - sock.close() - return None + device = (addr[0], port, name) + if device not in found_devices: + found_devices.append(device) + print(f"Found TV: '{name}' at {addr[0]}:{port}") + except socket.timeout: + break + except Exception: + pass + + sock.close() + return found_devices def connect(ip, port=8121): print(f"Connecting to {ip}:{port}...") @@ -127,11 +166,21 @@ def main(): if len(sys.argv) > 2: tv_port = int(sys.argv[2]) else: - found = discover() - if found: - tv_ip, tv_port, _ = found - else: + devices = discover() + if not devices: + print("No TVs discovered.") tv_ip = input("Enter TV IP address manually: ").strip() + elif len(devices) == 1: + tv_ip, tv_port, name = devices[0] + print(f"Auto-selected TV: '{name}' ({tv_ip}:{tv_port})") + else: + print(f"\nFound {len(devices)} TVs:") + for idx, (ip, port, name) in enumerate(devices, 1): + print(f" [{idx}] {name} ({ip}:{port})") + choice = input(f"Select TV [1-{len(devices)}] (default 1): ").strip() + idx = int(choice) - 1 if choice.isdigit() and 1 <= int(choice) <= len(devices) else 0 + tv_ip, tv_port, name = devices[idx] + print(f"Selected TV: '{name}' ({tv_ip}:{tv_port})") if not tv_ip: print("No IP provided. Exiting.")