import asyncio, sys, ipaddress

PORTS = [int(x) for x in sys.argv[1].split(',')]
SUBNETS = sys.argv[2].split(',')
CONC = int(sys.argv[3]) if len(sys.argv) > 3 else 200
SEM = asyncio.Semaphore(CONC)
OUT = []


async def probe(ip, port):
    async with SEM:
        w = None
        try:
            r, w = await asyncio.wait_for(asyncio.open_connection('127.0.0.1', 1080), 8)
        except Exception:
            return
        try:
            w.write(b'\x05\x01\x00')
            await w.drain()
            if await asyncio.wait_for(r.readexactly(2), 5) != b'\x05\x00':
                return
            w.write(b'\x05\x01\x00\x01' + ipaddress.IPv4Address(ip).packed + port.to_bytes(2, 'big'))
            await w.drain()
            head = await asyncio.wait_for(r.readexactly(4), 6)
            if head[1] != 0:
                return
            atyp = head[3]
            if atyp == 1:
                await asyncio.wait_for(r.readexactly(6), 5)
            elif atyp == 3:
                n = await asyncio.wait_for(r.readexactly(1), 5)
                await asyncio.wait_for(r.readexactly(n[0] + 2), 5)
            else:
                await asyncio.wait_for(r.readexactly(18), 5)
            OUT.append((ip, port))
        except Exception:
            pass
        finally:
            if w is not None:
                try:
                    w.close()
                except Exception:
                    pass


async def main():
    tasks = []
    for sn in SUBNETS:
        for ip in ipaddress.ip_network(sn).hosts():
            for p in PORTS:
                tasks.append(asyncio.create_task(probe(str(ip), p)))
    await asyncio.gather(*tasks)
    OUT.sort(key=lambda x: (tuple(int(o) for o in x[0].split('.')), x[1]))
    for ip, p in OUT:
        print('%s\t%d' % (ip, p))

asyncio.run(main())
