Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. import sys
  2. import struct
  3. import asyncio
  4.  
  5. @asyncio.coroutine
  6. def tcp_echo_client(server, port, loop):
  7.     try:
  8.         try:
  9.             reader, writer = yield from asyncio.wait_for(
  10.                 asyncio.open_connection(server, port, loop=loop),
  11.                 30.0,
  12.                 loop=loop
  13.             )
  14.         except asyncio.TimeoutError:
  15.             print('Timeout while establishing a connection')
  16.             return
  17.         writer.write(struct.pack('!H', port))
  18.         yield from writer.drain()
  19.  
  20.         try:
  21.             data = yield from asyncio.wait_for(
  22.                 reader.readexactly(6),
  23.                 30.0,  # Timeout after 30 seconds
  24.                 loop=loop
  25.             )
  26.             res = struct.unpack('!BBBBH', data)
  27.             remote_ip, port_used = res[0:4], res[4]
  28.             print('Connection established on port: {}'.format(port_used))
  29.             print('Egress IP address: {}'.format('.'.join(map(str, remote_ip))))
  30.         except asyncio.TimeoutError:
  31.             print('Timeout waiting for response')
  32.         except asyncio.IncompleteReadError:
  33.             print('Error receiving data')
  34.         finally:
  35.             writer.close()
  36.     except ConnectionError:
  37.         print('Error during connection on port {}'.format(port))
  38.  
  39. def main():
  40.     server_name = sys.argv[1]
  41.     try:
  42.         port = int(sys.argv[2])
  43.         if port < 1 or port > 65536:
  44.             raise ValueError()
  45.     except ValueError:
  46.         print('Error: invalid port value. Admissible range [0-65536]')
  47.         sys.exit()
  48.     loop = asyncio.get_event_loop()
  49.     loop.run_until_complete(tcp_echo_client(server_name, port, loop))
  50.     loop.close()
  51.     sys.exit()
  52.  
  53. if __name__ == '__main__':
  54.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement