1#!/bin/sh 2"exec" "`dirname $0`/py3-cmd" "$0" "$@" 3 4import argparse 5import socket 6 7# ADB expects its first console on 5554, and control on 5555 8ADB_BASE_PORT = 5554 9 10 11def alloc_adb_ports(min_port=ADB_BASE_PORT, num_ports=2): 12 """Allocates num_ports sequential ports above min_port for adb 13 14 adb normally uses ports in pairs. The exception is when a 15 port is needed for forwarding the adb connection, such as when 16 using a VM. 17 """ 18 19 # We can't actually reserve ports atomically for QEMU, but we can at 20 # least scan and find two that are not currently in use. 21 while True: 22 alloced_ports = [] 23 for port in range(min_port, min_port + num_ports): 24 # If the port is already in use, don't hand it out 25 try: 26 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 27 sock.connect(("localhost", port)) 28 break 29 except IOError: 30 alloced_ports += [port] 31 if len(alloced_ports) == num_ports: 32 return alloced_ports 33 34 # We could increment by only 1, but if we are competing with other 35 # adb sessions for ports, this will be more polite 36 min_port += num_ports 37 38 39if __name__ == "__main__": 40 argument_parser = argparse.ArgumentParser() 41 argument_parser.add_argument("--min-port", required=True, type=int) 42 argument_parser.add_argument("--num-ports", required=True, type=int) 43 args = argument_parser.parse_args() 44 45 ports = alloc_adb_ports(args.min_port, args.num_ports) 46 print(*ports, sep=" ") 47