# This program can be used to create a TCP connection to any port of a host
# It is mainly used for testing the connectivity of the host
#
# Author: Yi Hu

import socket
import sys

class TcpClient:
    def __init__(self, host:str, port:str):
        self.host = host # remote host address
        self.port = port # port listening on the remote host


    def connect_and_test_host(self):
        # create a socket object
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # connect the target
        client.connect((self.host, self.port))

        # send some data
        client.send(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')

        # receive some data
        response = client.recv(80000)

        print(response.decode())
        client.close()

if __name__ == '__main__':
    # check to see if the user gives required command line parameters
    if len(sys.argv) < 3:
        print('Command usage: python tcp_client.py hostname port')
        sys.exit(0)

    # get user input of host and port
    host = sys.argv[1]
    port = int(sys.argv[2])

    # connect to the host's port
    client = TcpClient(host, port)
    client.connect_and_test_host()

