#!/usr/bin/env python
from __future__ import print_function
import sys, os, time
from socket import *
import getopt

def try_connect(host,port):
    try:
        s=socket(AF_INET,SOCK_STREAM)
        s.connect((host,port))
        return s
    except:
        s.close()
        return None

# Options:
#
# -t timeout
# -h host
# -p port

t = now = time.time()
opts = dict(getopt.getopt(sys.argv[1:],'t:h:p:')[0])

host = opts['-h']
port = int(opts['-p'])
timeout = float(opts['-t'])

while time.time() < now + timeout:
      time.sleep(1)
      s = try_connect(host, port)
      if s:
          print(s.recv(32767).decode('utf-8'),end='')
          exit(0)
exit(1)
