Exemplo n.º 1
0
def init_trig_with_BuzzandTemp(motion):
    """
    Waits up to 4 seconds until corresponding sensor is triggered.
    If sensor triggered and temperature sensor not been triggered prior,
    buzzer will go off.
    If had triggered prior, direction of movement sent as message to server.

    Parameters:
    motion(int): Second motion sensor pin
    """
    for x in range(40):
        # Loop for 40 iterations.
        time.sleep(0.1)
        # Delay for 10ms.
        if (GPIO.input(motion) == 1):
            # Determines if corresponding motion sensor is triggered.
            if (motion == 1) and (!tempSensor.scanned):
                # Determines if user enters without temp scan.
                GPIO.setup(buzzerPin, GPIO.OUT)
                # Set buzzerPin to output mode.
                GPIO.output(buzzerPin, GPIO.HIGH)
                # Set buzzerPin high.
                time.sleep(2)
                # Delay for 2 seconds.
                GPIO.output(buzzerPin, GPIO.LOW)
                # Set buzzerPin low.
                print("BUZZ")
                break
            else:
                TCP.client(str(motion))
                # Sends direction of motion as message to the connected server.
                tempSensor.scanned = False
                break
Exemplo n.º 2
0
def speed(time, distance):
    """
    Calculates and sends speed as a message to server.

    Parameters:
    time(float): Time given in seconds
    distance(float): Distance given in meters
    """
    speed = distance/time
    # Calculates speed in meters/second.
    TCP.client(str(speed))
Exemplo n.º 3
0
def init_trig(motion):
    """
    Waits up to 4 seconds until corresponding sensor is triggered.
    motion(int): Second motion sensor pin
    """
    for x in range(40):
        # Loop for 40 iterations.
        time.sleep(0.1)
        # Delay for 10ms.
        if (GPIO.input(motion) == 1):
            # Determines if corresponding motion sensor is triggered.
                TCP.client(str(motion))
                # Sends direction of motion as message to the connected server.
                break
    def open(self):

        if self.enable:

            logger.debug('Opening {} TCP.'.format(self.name))
            # check for an old socket and delete it
            if self.sock is not None:
                logger.debug('Closing previously open sock.')
                try:
                    self.sock.close()
                except Exception as e:
                    logger.debug('Ignoring exception during sock.close() of previously open sock.\n{}\n'.format(e))
                try:
                    del self.sock
                except Exception as e:
                    logger.debug('Ignoring exception during sock.close() of previously open sock.\n{}\n'.format(e))

            # Create a TCP/IP socket
            logger.debug('{}.open() opening sock'.format(self.name))
            try:
                self.sock = TCP.CsClientSock(self.IP, self.port, parent=self)
            except Exception as e:
                logger.warning('Failed to open TCP socket in {}.open():\n{}\n'.format(self.name, e))
                raise PauseError
            logger.debug('{}.open() sock opened'.format(self.name))
            self.connected = True
def client():
    s = TCP.make_socket(9800, TCP.AF_INET, 0.9)
    print('bind', s.bind())
    print(s.connect(socket.gethostname(), 10000))
    print(s.dest_addr)

    print('timeout interval', s.estimated_RTT + s.dev_RTT * 4)
Exemplo n.º 6
0
def tcp_conn(netid, port, tout):
    global proto
    i = 1
    a = []

    print("Gathering host IP's now, remember that patience is a virtue...")
    try:
        stime = time.time()
        while i < 255:
            host = netid + "." + str(i)
            if TCP.connect(host, port, tout):
                a.append(host)
            i += 1
        etime = time.time()
        duration = etime - stime
    except socket.error:
        print("A socket error has occured, exiting")
        sys.exit(0)
    except KeyboardInterrupt:
        sys.exit(0)

    # Print awake hosts, if any.
    print("Tests took " + str(int(duration)) + " seconds with a " + str(tout) +
          " timeout")
    if len(a) > 0:
        print("The following hosts are running " + proto +
              " server software :")
        # Do not sort array, it's already done due to i var being incremented.
        for x in a:
            print(x)
    else:
        print("No hosts are awake or they're just not responding to " + proto +
              " requests")
def server():
    if len(sys.argv) != 2:
        print("Error: insertion of arguments file missed!")
        exit()

    server_port_number,                 \
    sending_sliding_window_size,        \
    random_generate_seed_value,         \
    loss_probability = get_server_data()

    w = int(sending_sliding_window_size)

    tcp_socket = TCP.make_socket(int(server_port_number), TCP.AF_INET,
                                 float(loss_probability), w, True)
    print("PLP :", tcp_socket.loss_probability)
    print("")

    if not tcp_socket.bind():
        print("Error : Cannot bind a busy port !")
        exit()

    while True:
        success_flag, s = tcp_socket.accept()

        if success_flag:
            print("Client Accepted !")
            serverThread(s).start()
Exemplo n.º 8
0
def Pack_tcp_packet(ip_src,port_src,ip_dst,port_dst,mac_src,mac_dst,flags,**kwargs):
	
	tcp = TCP.TCP(ip_src,port_src,ip_dst,port_dst,"")
	if "urg" in flags:
		tcp.set_urg()
	if "ack" in flags:
		tcp.set_ack()
	if "psh" in flags:
		tcp.set_psh()
	if "rst" in flags:
		tcp.set_rst()
	if "syn" in flags:
		tcp.set_syn()
	if "fin" in flags:
		tcp.set_fin()
	if "acknowledgment_number" in kwargs:
		tcp.acknowledgment_number = kwargs["acknowledgment_number"] 
	if "sequence_number" in kwargs:
		tcp.sequence_number = kwargs["sequence_number"]
	if "payload" in kwargs:
		tcp.payload= kwargs["payload"]
	tcp_header = tcp.Pack()
	ip = IP.IP(ip_src,ip_dst,tcp_header)
	ip_header = ip.Pack()
	mac_src = Convert_mac_address(mac_src)
	mac_dst = Convert_mac_address(mac_dst)
	ethernet = Ethernet.Ethernet(mac_src,mac_dst,0x0800,ip_header)
	packet = ethernet.Pack()
	return packet,tcp.sequence_number
Exemplo n.º 9
0
    def initialize(self):
        """Open the TCP socket"""
        if self.enable:
            self.socket = TCP.CsClientSock(self.IP, self.port)

            # TODO: add here some sort of communications check to see if it worked

            self.isInitialized = True
Exemplo n.º 10
0
def sendRecording(file_path):
	AWS_socket = tcp.TCPsocket()
	AWS_socket.connect(AWS_IP, AWS_FILE_PORT)
	try:
		AWS_socket.sendFile(file_path)
		os.remove(file_path)
	except:
		print("Error sending file: " + file_path)
		pass
def client():

    if len(sys.argv) != 2:
        print(bcolors.FAIL + "Error: insertion of arguments file missed!" +
              bcolors.ENDC)
        exit()

    server_ip, server_port_number, client_port_number, file_name, receiveing_sliding_window_size = get_client_data(
    )
    s = TCP.make_socket(int(client_port_number), TCP.AF_INET,
                        0)  # check for IPv6

    if not s.bind():
        print(bcolors.FAIL +
              "error : please change port number [ port busy ] " +
              bcolors.ENDC)
        exit(1)

    if server_ip == "localhost":
        s.connect(socket.gethostname(), int(server_port_number))
    else:
        s.connect(server_ip, int(server_port_number))

    s.send(file_name)
    data = s.receive()

    if data == "error":
        print(bcolors.FAIL + "Error: File not Found !" + bcolors.ENDC)
    else:
        file = open(file_name.split("\\")[-1], "ab")

        num_of_packets = int(data)
        print('Number of packets :', num_of_packets)

        before = time.time()

        for i in range(0, num_of_packets, 1):
            data = s.receive()

            percentage = int(i * 100 / num_of_packets)
            my_print(percentage, i, num_of_packets, True)

            file.write(data)

        reception_time = time.time() - before

        my_print(100, num_of_packets, num_of_packets, False)

        print("Success: File Reception Completed !")

        s.close()

        print("\nStatistics :-")
        print("Reception Time =", "{0:.2f}".format(reception_time), "Sec")
        print("Average Speed =",
              "{0:.2f}".format(num_of_packets / reception_time), "Packets/Sec")
def server():
    s = TCP.make_socket(10000, TCP.AF_INET, 0.9)
    print('bind', s.bind())
    flag, another_server = s.accept()

    print(flag)
    print(another_server)
    print(another_server.dest_addr)

    print('timeout interval', s.estimated_RTT + s.dev_RTT * 4)
Exemplo n.º 13
0
class RemotePlayer(Player):
    #gets information on moves from a remote player using a TCP socket server and stuff
    #needs to be player 2 in the game
    
    def __init__(self, game):
        self.tcp = TCP("127.0.0.1", "5005")
        self.game.players[0].set_connection(self.tcp)
        
    def select_piece(self):
        data = self.tcp.receive_piece()
        while data == None:
            print "No data received"
        return int(data)
    
    def select_position(self, piece):
        data = self.tcp.receive_position()
        while data == None:
            print "No data received"
        return int(data)
Exemplo n.º 14
0
class RemotePlayer(Player):
    #gets information on moves from a remote player using a TCP socket server and stuff
    #needs to be player 2 in the game

    def __init__(self, game):
        self.tcp = TCP("127.0.0.1", "5005")
        self.game.players[0].set_connection(self.tcp)

    def select_piece(self):
        data = self.tcp.receive_piece()
        while data == None:
            print "No data received"
        return int(data)

    def select_position(self, piece):
        data = self.tcp.receive_position()
        while data == None:
            print "No data received"
        return int(data)
Exemplo n.º 15
0
def feverScanner(maxtemp):
    """
    Determines if an individual is standing infront of the temperature sensor,
    waits a full second and reads the temperature value again to gain a more
    stable value. Also determines if temperature is above that of the norm.
    This data is relayed as a message to the server.
    """
    global init
    global scanned
    tempReading()
    if (tdata[0] > roomtemp) and (tdata[0] > 30):
        if (!init):
            init = True
            feverScanner()
        else:
            init = False
            scanned = True
            TCP.client(str(tdata[0]))
            if (tdata[0]) > maxtemp:
                scanned = False
                time.sleep(1)
Exemplo n.º 16
0
def UnPack_tcp_packet(packet):
		
	tcp = None
	try:
		ethernet = Ethernet.Ethernet("","","","")
		ethernet_payload = ethernet.UnPack(packet)
	        ip = IP.IP("","","")
	        ip.UnPack(ethernet.Ethernet_payload)
        	tcp = TCP.TCP("","","","","")
	        tcp.UnPack(ip.payload)
				
	except Exception,e:
		return None
Exemplo n.º 17
0
    def __init__(self, GaiaZomgLib, IP='208.85.93.217', PORT=8080):
        self.GaiaZomgLib = GaiaZomgLib

        self.IP = IP
        self.PORT = PORT
        self.TCP = TCP.TCPClient()#(IP, PORT, 1024) 

        self.decoding_thread = threading.Thread(target=self.decode_packets)
        #self.decoding_thread.start()

        self.CID = 4

        self.event_packet_decoded = Event()
Exemplo n.º 18
0
 def __init__(self, IP="0.0.0.0", volume_port=5005, dance_port=4204):
     self.IP = IP
     self.dance_port = dance_port
     self.volume_port = volume_port
     self.danceDataQueue = queue.Queue()
     self.audioFileQueue = queue.Queue()
     self.commandQueue = queue.Queue()
     self.audioConnection = tcp.TCPsocket()
     #get rid of this try block
     try:
         self.audioConnection.listen(self.IP, self.volume_port)
     except:
         print("WTFWTFWTF")
         pass
Exemplo n.º 19
0
def controlInterface():
	try:
		AWS_socket = tcp.TCPsocket()
		AWS_socket.connect(AWS_IP, AWS_COMMAND_PORT)
		print("Connected to AWS control interface on port " + str(AWS_COMMAND_PORT))
		while True:
			message = AWS_socket.receiveMessage()
			if message.lower() == "file":
				AWS_socket.sendFile(RECORD_QUEUE.get())
			elif message in COMMANDS:
				# AWS_socket.sendMessage("Received: " + message)
				COMMAND_QUEUE.put(message)
				if message.lower() == "stop":
					AWS_socket.closeSocket()
					break
			else:
				AWS_socket.sendMessage("Invalid command: " + message)
	except:
		print("Lost connection to AWS control interface")
		global LOST_CONNECTION_FLAG
		LOST_CONNECTION_FLAG = 1
def validatePacket(packet):

    if not IP.validateChecksumZero(packet[0:20]):
        return False, "IP"
    else:
        print "IP VALIDATION: SUCCESS"

    ip_header = IP.unpackHeader(packet[0:20])
    #Get Length of IP header
    ip_ver = ip_header[0] >> 4
    ip_header_length = ip_header[0] & 0xF
    ip_length = ip_header_length * 4

    tcp_packet = packet[ip_length:]
    pseudo = pack('!4s4sBBH', ip_header[8], ip_header[9], 0, socket.IPPROTO_TCP, len(tcp_packet))

    if not TCP.validateChecksumZero(pseudo + tcp_packet):
        return False, "TCP"
    else:
        print "TCP VALIDATION: SUCCESS"

    return True, ""
Exemplo n.º 21
0
import TCP

server = TCP.ThreadedServer('192.168.22.1',5000,62)
server.listen()
Exemplo n.º 22
0
def getACK(source_ip, destination_ip, packet_id, source_port, destination_port, SEQ_NUM, ACK_NUM, data, window_size):
    tcp_header = TCP.createTCPHeader(source_ip, destination_ip, source_port, destination_port, SEQ_NUM, ACK_NUM, data, window_size, [0, 0, 0, 0, 1, 0])
    ip_header = IP.createIPHeader(source_ip, destination_ip, packet_id, tcp_header, data)
    packet = ip_header + tcp_header + data
    return packet
Exemplo n.º 23
0
 def __init__(self, game):
     self.tcp = TCP("127.0.0.1", "5005")
     self.game.players[0].set_connection(self.tcp)
Exemplo n.º 24
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*

from TCP import *

servidor = TCP()

servidor.server('localhost', 45000)
Exemplo n.º 25
0
    output = a.stdout.read()
    a.stdout.close()
    a.stdin.close()
    return output


##########################################
#MAIN
##########################################

if __name__ == "__main__":
    begin_flag = 1
    audioStream = threading.Thread(
        target=runFileServer)  # should this be processs or thread ?
    audioStream.start()
    visualizer = tcp.TCPsocket()
    visualizerThread = threading.Thread(target=visualizer.listen,
                                        args=[IP, VISUALIZER_PORT])
    visualizerThread.start()

    mainInterface = CentralIO()
    danceIOThread = threading.Thread(target=mainInterface.danceServer)
    #danceIOThread.start()
    volumeControl = VolumeController()
    audioIOThread = threading.Thread(target=mainInterface.audioIO)
    audioIOThread.start()
    volume = 5  # set this as the begining
    epoch = 0
    while (True):

        epoch += 1
Exemplo n.º 26
0
    def connect(
            self,
            remote_address):  # real signature unknown; restored from __doc__
        """
        connect(address)

        Connect the socket to a remote address.  For IP sockets, the address
        is a pair (host, port).
        """

        # init remote_address
        self.__remote_address = remote_address

        # connect to IP layer
        print('connecting to IP layer')
        self.__ip = IP.IP(IP.PROTOCOL_TCP,
                          self.__local_address[0],
                          dst_ip=remote_address[0])
        print('connected to IP layer')

        # generate client_isn
        self.__isn = random.randint(0, 2147483645)
        client_isn = self.__isn
        print('generated isn', self.__isn)

        # build a tcp object with SYN
        tcp = TCP()
        tcp.build(type=tcp.SEND_SYN,
                  src_port=self.__local_address[1],
                  dst_port=remote_address[1],
                  sequence_number=self.__isn)

        # sign a space in buffer_list
        buffer_list['connecting'][remote_address] = []

        # sent tcp object
        self.__ip.send(bytes(tcp))
        print('sent tcp object')

        # record first_package_sent_time
        first_package_sent_time = time.time()

        # wait for sencond hanshake
        print('waiting for sencond hanshake')
        star_time = time.time()
        flag_3 = True
        flag_6 = False
        flag_12 = False

        while buffer_list['connecting'][remote_address] == []:
            if flag_3 and time.time() - star_time >= 2:
                print('3s timeout')
                self.__ip.send(bytes(tcp))
                flag_3 = False
                flag_6 = True
                star_time = time.time()
            elif flag_6 and time.time() - star_time >= 2:
                print('6s timeout')
                self.__ip.send(bytes(tcp))
                flag_6 = False
                flag_12 = True
                star_time = time.time()
            elif flag_12 and time.time() - star_time >= 2:
                print('12s timeout')
                self.__ip.send(bytes(tcp))
                flag_12 = False
                star_time = time.time()
            elif time.time() - star_time >= 4:
                print('break')
                return
            continue

        self.status = 'established'
        # record first_package_receive_time
        self.__sample_RTT = time.time() - first_package_sent_time
        self.__estimated_RTT = self.__sample_RTT
        self._get_new_timeout()
        print('fisrt sampleRTT inited, it\'s', self.__sample_RTT)

        # retrive data
        data = buffer_list['connecting'][remote_address].pop()
        print('retrived')

        # parse tcp object
        tcp = TCP()
        tcp.from_bytes(data)

        # check tcp object is right
        if not (tcp.SYN == 1 and tcp.ACK == 1
                and tcp.acknowledgement_number == client_isn + 1):
            print('the tcp object is not right. Connect failed')
            return

        # if it's right, update server_isn, client_isn
        server_isn = tcp.sequence_number
        client_isn += 1
        self.__next_sequence_number = client_isn
        print('client_isn sent', client_isn)
        self.__last_ack_received = tcp.acknowledgement_number

        # remove from buffer_list['connecting'], added to buffer_list['connected']
        buffer_list['connecting'].pop(remote_address)
        buffer_list['connected']['objects'][remote_address] = self

        # generate last_ack_sent and update ack_to_be_sent list, last_ack_received
        self.__last_acked_sent = server_isn + 1
        self.__ack_to_be_sent.append(self.__last_acked_sent)

        # start sending thread
        self.__sending_process = threading.Thread(target=self._sending_thread)
        self.__sending_process.start()
        print('connected')
Exemplo n.º 27
0
    def _sending_thread(self):
        # build empty tcp object
        tcp = TCP()
        tcp.build(type=tcp.SEND_DATA,
                  src_port=self.__local_address[1],
                  dst_port=self.__remote_address[1])
        tcp.sequence_number = self.__next_sequence_number
        tcp.acknowledgement_number = self.__last_acked_sent
        print('built empty tcp object')

        while 1:
            time.sleep(0.2)
            # print('sending thread begin')
            # detect whether there is act_to_be_sent
            if self.__ack_to_be_sent != []:
                tcp.ACK = 1
                tcp.acknowledgement_number = self.__ack_to_be_sent.pop()
                self.__last_acked_sent = tcp.acknowledgement_number
                print(
                    'detect there is ack_to_be_sent({}), added to current tcp object, last_acked_number updated'
                    .format(tcp.acknowledgement_number))

            # check time_out
            if self.__is_time_out:
                print('detect time out')

                # get first send_but_not_acked data in tcp.data
                try:
                    tcp_bytes = self.__sent_but_not_acked[0]

                    tcp = TCP()
                    tcp.from_bytes(tcp_bytes)

                    # modify tcp.sequence_number
                    # tcp.sequence_number = waiting_ack_number - len(tcp.data)

                    # double timeout
                    self.__time_out *= 2

                    if self.__time_out <= 1:
                        self.__time_out = 1

                    # cancel SampleRTT recording for this object
                    self.__sample_RTT_to_record[tcp.sequence_number +
                                                len(tcp.data)] = None

                    # Done with here
                    self.__is_time_out = False

                    self.__timer = threading.Thread()
                    self.__timer_pid = None

                    print(self.__time_out)
                except:
                    self.__is_time_out = False

                    self.__timer = threading.Thread()
                    self.__timer_pid = None
            else:
                # print('no timeout detected')

                # calculate the spare room in sent_but_not_acked
                spare_room_in_window = self.__window_size - (
                    self.__next_sequence_number - self.__last_ack_received)

                if self.__send_buffer != b'' and spare_room_in_window != 0:  # specify squence number andNextSeqNum
                    NextSeqNum = self.__next_sequence_number

                    # prepare data
                    data = self.__send_buffer[:self.__segment_size]

                    # delete that data from send_buffer
                    self.__send_buffer = self.__send_buffer[self.
                                                            __segment_size:]

                    # update tcp object
                    tcp.data = data
                    tcp.sequence_number = NextSeqNum

            # check tcp modified
            if tcp.data != b'' or tcp.ACK == 1:
                # set sequence number
                # tcp.sequence_number = self.__next_sequence_number

                # if data included, update next_sequence_number
                if tcp.data != b'':
                    self.__next_sequence_number += len(data)

                # if the tcp contains data
                if tcp.data != b'':
                    # check the data is first sent or not

                    # add current value to sent_but_not_acked
                    if bytes(tcp) not in self.__sent_but_not_acked:
                        self.__sent_but_not_acked.append(bytes(tcp))

                    if (tcp.sequence_number + len(tcp.data)
                        ) not in self.__sample_RTT_to_record.keys():
                        # it's first sent.

                        # record send time
                        send_time = time.time()
                        self.__sample_RTT_to_record[tcp.sequence_number +
                                                    len(tcp.data)] = send_time
                        # print('----------')
                        # print('record time')
                        # print(self.__sample_RTT_to_record)
                        # print('----------')

                        # check whether there is already a tiemr
                        print('check timer', self.__timer.is_alive())
                        if not self.__timer.is_alive():
                            # there is no timer

                            # calculate a new time_out
                            self.__time_out = self._get_new_timeout()

                            # start a new timer
                            self.__timer = threading.Thread(
                                target=self.__check_time,
                                args=(time.time(), self.__time_out))
                            self.__timer.start()
                    else:
                        # it's not first sent

                        # double timeout
                        print(
                            'detect not first send message, the sequence_number is {}, the ack_number is {}, content:{}'
                            .format(tcp.sequence_number,
                                    tcp.acknowledgement_number, str(tcp)))
                        print(self.__sample_RTT_to_record)
                        self.__time_out *= 2
                        self.__timer = threading.Thread(
                            target=self.__check_time,
                            args=(time.time(), self.__time_out))
                        self.__timer.start()

                # send tcp object
                self.__ip.send(bytes(tcp))
                print(
                    'send tcp object with \tsequence number {} and \tacknowledge number {}.'
                    .format(tcp.sequence_number, tcp.acknowledgement_number))
                print('content', str(tcp))

                # build new tcp object
                tcp = TCP()
                tcp.build(type=tcp.SEND_DATA,
                          src_port=self.__local_address[1],
                          dst_port=self.__remote_address[1])
                tcp.sequence_number = self.__next_sequence_number
                tcp.acknowledgement_number = self.__last_acked_sent
Exemplo n.º 28
0
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 29 10:21:07 2016

@author: mb22
"""

import TCP
import matplotlib.pyplot as plt
import importlib
importlib.reload(TCP)

TCP = 88
n = 500
alphabeta_use = 3
alphabeta_sd_use = 0.5
d = 2
d_shift = 0
d_sd = 0.5
d_trend = 0
max_d = 100
dose_of_interest = 74
TCP_input = 88
   


xyz =  TCP.calc_dif_sq(x,TCP, n, alphabeta_use, alphabeta_sd_use,d,d_shift,d_sd,d_trend,max_d,dose_of_interest,TCP_input)
    
Exemplo n.º 29
0
    def accept(self):
        """accept() -> address tuple, server_isn int

        Wait for an incoming connection.  Return a new socket
        representing the connection, and the address of the client.
        For IP sockets, the address info is a pair (hostaddr, port).
        """
        # fd, addr = self._accept()
        # If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the
        # new socket. We do not currently allow passing SOCK_NONBLOCK to
        # accept4, so the returned socket is always blocking.
        # type = self.type & ~globals().get("SOCK_NONBLOCK", 0)
        # sock = socket(self.family, type, self.proto, fileno=fd)
        # Issue #7995: if no default timeout is set and the listening
        # socket had a (non-zero) timeout, force the new socket in blocking
        # mode to override platform-specific socket flags inheritance.
        # if getdefaulttimeout() is None and self.gettimeout():
        #     sock.setblocking(True)
        # return address, server_isn

        # if not self.__address:
        #     raise AddressNotSpecified("Did you bind address for this socket?")

        # wait until one connected
        while buffer_list['listening'][self.__local_address[1]]['queue'] == []:
            continue

        # retrive first handshake
        data, (remote_ip, remote_port) = buffer_list['listening'][
            self.__local_address[1]]['queue'].pop()
        tcp = TCP()
        tcp.from_bytes(data)
        if not (tcp.SYN == 1 and tcp.ACK == 0):
            # print("wrong tcp package received, it's not the first handshake")
            return
        client_isn = tcp.sequence_number
        print('first handshake received')

        # reformat remote_address
        address = (remote_ip, tcp.src_port)

        # generate a inital server_isn
        server_isn = random.randint(0, 2147483645)

        # build a tcp with server_isn and client_isn + 1
        tcp = TCP()
        tcp.build(type=tcp.SEND_SYNACK,
                  src_port=self.__local_address[1],
                  dst_port=address[1],
                  sequence_number=server_isn,
                  acknowledgement_number=client_isn + 1)

        # send the second handshake and register a place for handshake
        tmp_ip = IP.IP(IP.PROTOCOL_TCP, self.__local_address[0], remote_ip)
        tmp_ip.send(bytes(tcp))
        buffer_list['connecting'][address] = []
        print('second handshake sent, waiting for the third handshake')

        # record the first time of send package
        fisrt_pacakge_sent_time = time.time()

        # wait until third handshake appear
        send_send_start_time = time.time()
        flag_3 = True
        flag_6 = False
        flag_12 = False
        while buffer_list['connecting'][address] == []:
            if flag_3 and (time.time() - send_send_start_time >= 2):
                print('waiting second hand time out, wait another 6s')
                tmp_ip.send(bytes(tcp))
                send_send_start_time = time.time()
                flag_3 = False
                flag_6 = True
                send_send_start_time = time.time()
            elif flag_6 and (time.time() - send_send_start_time >= 2):
                print('waiting second hand time out, wait another 12s')
                tmp_ip.send(bytes(tcp))
                send_send_start_time = time.time()
                flag_6 = False
                flag_12 = True
                send_send_start_time = time.time()
            elif flag_12 and (time.time() - send_send_start_time >= 2):
                print('waiting second hand time out, wait another 24s')
                tmp_ip.send(bytes(tcp))
                flag_6 = False
                flag_12 = False
                send_send_start_time = time.time()
            elif (time.time() - send_send_start_time >= 4):
                print('waiting second hand time out, wait another 6s')
                print('break')
                return

            continue

        # record the time of receiving second package
        self.__sample_RTT = time.time() - fisrt_pacakge_sent_time
        self.__estimated_RTT = self.__sample_RTT
        print('first sample RTT generated, it\'s {}'.format(self.__sample_RTT))

        # retrive the third handshake
        data, address = buffer_list['connecting'][address].pop()
        tcp = TCP()
        tcp.from_bytes(data)
        print('third handshake retrived')

        # check third handshake
        if not (tcp.sequence_number == client_isn + 1
                and tcp.acknowledgement_number == server_isn + 1):
            print(
                'SYN {}, ACK{}, tcp.sequencenumber({}) ?= client_isn({}), tcp.acknowledgement_number({}) ?= server_isn({})'
                .format(tcp.SYN, tcp.ACK, tcp.sequence_number, client_isn + 1,
                        tcp.acknowledgement_number, server_isn + 1))
            print(
                "wrong tcp package received, it's not the correct third handshake"
            )
            return

        # update server_isn
        server_isn += 1

        # open a place for the newly connected socket
        buffer_list['connected'][address] = []

        # delete the original space
        buffer_list['connecting'].pop(address)

        # add data to the buffer if any

        # buffer_list['connected'][address].append(tcp.data)

        # Build a new tcpSocket
        tcpSocket = TCPsocket(self.__local_address, address, server_isn,
                              client_isn + 1, self.__sample_RTT)

        # put the conneceted object in buffer
        buffer_list['connected']['objects'][address] = tcpSocket

        # add data if any
        if tcp.data != b'':
            tcpSocket._add_data(tcp.data)
        print('done with accept, returned address and server_isn')

        return address, tcpSocket
Exemplo n.º 30
0
import GUI
import TCP
from tkinter import messagebox
if __name__ == "__main__":
    gui = GUI.App()
    gui.wm_title("TCP")
    tcp = TCP.TCP(gui)
    gui.set_tcp(tcp)

    def on_closing():
        if messagebox.askokcancel(
                "TCP-protocol",
                "Are you sure you want to terminate the connection?"):
            gui.destroy()

    gui.protocol("WM_DELETE_WINDOW", on_closing)

    gui.bind("<<CLOSED>>", gui.change_state_closed)
    gui.bind("<<LISTEN>>", gui.change_state_listen)
    gui.bind("<<SYN-RECEIVED>>", gui.change_state_syn_received)
    gui.bind("<<SYN-SENT>>", gui.change_state_syn_sent)
    gui.bind("<<ESTABLISHED>>", gui.change_state_established)
    gui.bind("<<FIN-WAIT-1>>", gui.change_state_fin_wait_1)
    gui.bind("<<FIN-WAIT-2>>", gui.change_state_fin_wait_2)
    gui.bind("<<TIME-WAIT>>", gui.change_state_time_wait)
    gui.bind("<<CLOSE-WAIT>>", gui.change_state_close_wait)
    gui.bind("<<LAST-ACK>>", gui.change_state_last_ack)

    gui.mainloop()
Exemplo n.º 31
0
    def _add_data(self, data):
        tcp = TCP()
        tcp.from_bytes(data)
        # print('retrived data from IP layer')

        # if has ack info
        if tcp.ACK == 1:
            # print("detect ACK info, it's", tcp.acknowledgement_number)
            if tcp.acknowledgement_number == self.__last_ack_received:
                # it's duplicated ack
                self.__duplicate_ack += 1
                print('detect {} duplicated ACK'.format(self.__duplicate_ack))
                if self.__duplicate_ack >= 3:
                    # fast retransmission

                    # stop timer and make timeout to be true
                    self.__timer = threading.Thread()
                    self.__timer_pid = None
                    self.__is_time_out = True
                    print(
                        'timer stoped, set timeout to be true, preparing for retransmission'
                    )
                    self.__duplicate_ack = 0
            else:
                self.__duplicate_ack = 0
                # it's not duplicated ack
                if tcp.acknowledgement_number > self.__last_ack_received:

                    print('current SendBase {}, updated to {}'.format(
                        self.__last_ack_received, tcp.acknowledgement_number))

                    # update SendBase
                    self.__last_ack_received = tcp.acknowledgement_number
                    self.__next_sequence_number = tcp.acknowledgement_number

                    # calculating a new SampleRTT
                    # print('----------')
                    # print('receive time')
                    # print(self.__sample_RTT_to_record)
                    # print('tcp info:')
                    # print('sequence_number:{}, acknowledgement_number:{}, content:{}'.format(tcp.sequence_number, tcp.acknowledgement_number, str(tcp)))
                    # print('----------')
                    try:
                        self.__sample_RTT = time.time(
                        ) - self.__sample_RTT_to_record[
                            tcp.acknowledgement_number]
                    except:
                        pass

                    # remove self.__send_but_not_acked objects according to the ack number
                    print('updating sent_but_not_acked list')
                    remove_list = []
                    for tcp_bytes in self.__sent_but_not_acked:
                        tcp_ = TCP()
                        tcp_.from_bytes(tcp_bytes)
                        if tcp_.sequence_number + len(
                                tcp_.data) <= tcp.acknowledgement_number:
                            remove_list.append(tcp_bytes)
                            print('removed waiting_ack_number:{}'.format(
                                tcp_.sequence_number + len(tcp_.data)))
                    for item in remove_list:
                        self.__sent_but_not_acked.remove(item)
                    # print('updated')

                    # check whether a timer is running
                    if self.__timer.is_alive():
                        print('detect a timer still running')

                        # check whether there are still sent_but_not_acked
                        if self.__sent_but_not_acked:
                            print('detect there is still sent_but_not_acked:')
                            print(self.__sent_but_not_acked)
                            print('restart timer')
                            self.__time_out = self._get_new_timeout()
                            # restart timer
                            self.__timer = threading.Thread(
                                target=self.__check_time,
                                args=(time.time(), self.__time_out))
                            self.__timer.start()
                        else:
                            # stop timer
                            self.__timer = threading.Thread()
                            self.__timer_pid = None
                            self.__is_time_out = False
                            self.__time_out = self._get_new_timeout()
                            print(
                                'no data in sent_but_note_acked, stopped timer'
                            )

        # if has data info:
        if tcp.data != b'':
            # check whether it's duplicate data
            if tcp.sequence_number < self.__last_acked_sent:
                print(
                    'the sequence_number({}) < last_acked_sent({}), omit it.'.
                    format(tcp.sequence_number, self.__last_acked_sent))
                # it's duplicate data
                tcp = TCP()
                tcp.build(type=tcp.SEND_ACK,
                          src_port=self.__local_address[1],
                          dst_port=self.__remote_address[1],
                          acknowledgement_number=self.__last_acked_sent)
                print('duplicate data, send ack')
            else:
                # it's not duplicate data

                # put it in self.__window_buffer and sort
                print(tcp.data, 'has added to window buffer')
                self.__window_buffer.append((tcp.sequence_number, tcp.data))
                self.__window_buffer.sort(key=lambda x: x[0])

                # check tmp_buffer in-order data, if any, put it to recv_buffer

                while self.__window_buffer[0][0] == self.__last_acked_sent:
                    # retrive from window_buffer(tmp_buffer)
                    sequence_number, data = self.__window_buffer.pop()

                    # calculate and update last_ack_sent
                    self.__last_acked_sent += len(data)

                    # put data into recv_buffer
                    self.__received_buffer += data
                    print(
                        'put data with sequence_number {} out of tmp_buffer into recv_buffer, updated last_ack_sent, waiting to be sent later'
                        .format(tcp.sequence_number))
                    if len(self.__window_buffer) == 0:
                        break

                # put last_ack_sent to ack_to_be_sent
                self.__ack_to_be_sent.append(self.__last_acked_sent)
                print('not duplicate, send ack', self.__last_acked_sent)
Exemplo n.º 32
0
import time
import TCP

########################################################################
## Main code
while True:
    try:
        TCP.SocketProcess()
    except:
        pass

    time.sleep(0.01)
Exemplo n.º 33
0
    def push(data, remote_ip):
        # print
        # print('[static method]received data from ip, it\'s from', remote_ip)
        tcp = TCP()
        tcp.from_bytes(data)
        # print('current buffer_list is')
        # print(buffer_list)

        # print('src_port is', tcp.src_port, end=' ')
        # print('dst_port is', tcp.dst_port, end=' ')
        # print('content is', str(tcp))

        # print()
        # print basic info
        # names = ['CWR','ECE','URG','ACK','PSH','RST','SYN','FIN']
        # byte = tcp.flag_bits
        # byte = bin(int.from_bytes(byte, 'little'))[2:]
        # print(bytes)
        # for i in range(8):
        #     print("{}:{}".format(names[i], byte[i]))
        #
        # if tcp.SYN == 1 and tcp.ACK != 1:
        #     b
        remote_address = (remote_ip, tcp.src_port)
        if tcp.RST:
            raise ConnectionResetError
        try:
            if tcp.SYN == 1 and tcp.ACK == 1:
                print('detect second handshake')
                try:
                    buffer_list['connecting'][remote_address].append(data)
                except:
                    server_isn = tcp.sequence_number
                    client_isn = tcp.acknowledgement_number
                    remote_port = tcp.src_port
                    local_port = tcp.dst_port
                    tcp = TCP()
                    tcp.sequence_number = client_isn
                    tcp.acknowledgement_number = server_isn
                    tcp.src_port = local_port
                    tcp.dst_port = remote_port
                    tmp_ip = IP.IP(protocol=IP.PROTOCOL_TCP,
                                   src_ip=local_ip,
                                   dst_ip=remote_ip)
                    print('retransmitted', tcp.sequence_number,
                          tcp.acknowledge_number)
                    print("str", str(tcp))
                    tmp_ip.send(bytes(tcp))

            elif tcp.SYN == 1:
                # it's first handshake
                print('detect first handshake')
                buffer_list['listening'][tcp.dst_port]['queue'].append(
                    (data, remote_address))
            else:
                # it's not first handshake

                # self.__last_acked_number = tcp.acknowledgement_number # todo update last_acked_number

                # check whether it's a third handshake
                if remote_address in buffer_list['connected']['objects'].keys(
                ):
                    print('detect normal message')
                    # it's not a third handshake
                    # buffer_list['connected'][remote_address].append((data, remote_address))

                    # get tcp object
                    obj = buffer_list['connected']['objects'][remote_address]

                    # let obj add data
                    obj._add_data(data)
                else:
                    # it's a third handshake
                    print('detect third handshake')
                    buffer_list['connecting'][remote_address].append(
                        (data, remote_address))
        except:
            local_port = tcp.dst_port
            remote_port = tcp.src_port
            sequence_number = tcp.acknowledgement_number
            acknowledge_number = tcp.sequence_number
            tcp = TCP()
            tcp.RST = 1
            tcp.ACK = 0
            tcp.src_port = local_port
            tcp.dst_port = remote_port
            tcp.sequence_number = sequence_number
            tcp.acknowledgement_number = acknowledge_number
            tmp_ip = IP.IP(protocol=IP.PROTOCOL_TCP,
                           src_ip=local_ip,
                           dst_ip=remote_ip)
            tmp_ip.send(bytes(tcp))
Exemplo n.º 34
0
 def __init__(self, game):
     self.tcp = TCP("127.0.0.1", "5005")
     self.game.players[0].set_connection(self.tcp)
Exemplo n.º 35
0
def main():

	# Parsing user input
	parser = argparse.ArgumentParser()
	parser.add_argument(
			'-p','--port',
			nargs='?',
			type=int,
			default=8118,
			help='TCP Port Number.'
		)
	parser.add_argument(
			'-i','--ip',
			nargs='?',
			type=str,
			default='127.0.0.1',
			help='TCP IP Address.'
		)
	parser.add_argument(
			'-b','--buffer_size',
			nargs='?',
			type=int,
			default=256,
			help='TCP Socket Buffer Size.'
		)
	parser.add_argument(
			'-m','--mode',
			nargs='?',
			action='store',
			default='client',
			choices=['client','server'],
			help='Client or Server mode.'
		)
	args = parser.parse_args()

	tcp = TCP(
		port		= args.port,
		ip			= args.ip,
		buffer_size	= args.buffer_size,
		mode		= args.mode,
	)


	# Keeps requesting the most recent data
	if(tcp.mode=='client'):
		try:
			for i in range(15):
				print i, yaml.load(tcp.request('kayak_0'))
				time.sleep(0.5)
		except:
			pass


	# Keeps providing the most recent data
	sim_update_secs = 0.010
	kayak_rotation_freque = 0.010
	glider_rotation_freque = 0.005
	if(tcp.mode=='server'):
		t = 0.000
		try:
			while True:
				t = time.time()
				tcp.database = {
					'kayak_0': yaml.dump({
							'Depth': 0.0,
							'Latitude': 32.0 	+ math.sin(kayak_rotation_freque*2*math.pi*t),
							'Longitude': -119.0	+ math.cos(kayak_rotation_freque*2*math.pi*t),
							'Salinity': 33.0	+ math.sin(0.25*2*math.pi*t),
							'Temperature': 16.0	+ math.sin(0.50*2*math.pi*t),
							'Time': t,
							'w': 1.0,
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						}),
					'kayak_1': yaml.dump({
							'Depth': 0.0,
							'Latitude': 32.0 	+ math.cos(kayak_rotation_freque*2*math.pi*t),
							'Longitude': -119.0	+ math.sin(kayak_rotation_freque*2*math.pi*t),
							'Salinity': 33.0	+ math.sin(0.25*2*math.pi*t),
							'Temperature': 16.0	+ math.sin(0.50*2*math.pi*t),
							'Time': t,
							'w': 1.0,
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						}),
					'glider_0': yaml.dump({
							'Depth': 50.0,
							'Latitude': 32.0 	+ math.sin(glider_rotation_freque*2*math.pi*t),
							'Longitude': -119.0	+ math.cos(glider_rotation_freque*2*math.pi*t),
							'Salinity': 33.0	+ math.sin(0.25*2*math.pi*t),
							'Temperature': 16.0	+ math.sin(0.50*2*math.pi*t),
							'Time': t,
							'w': 1.0,
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						}),
					'glider_1': yaml.dump({
							'Depth': 100.0,
							'Latitude': 32.0 	+ math.cos(glider_rotation_freque*2*math.pi*t),
							'Longitude': -119.0	+ math.sin(glider_rotation_freque*2*math.pi*t),
							'Salinity': 33.0	+ math.sin(0.25*2*math.pi*t),
							'Temperature': 16.0	+ math.sin(0.50*2*math.pi*t),
							'Time': t,
							'w': 1.0,
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						}),
				}
				t += sim_update_secs
				time.sleep(sim_update_secs)
				
		except:
			tcp.exit_server()
        packet = receiver_socket.recvfrom(65565)
        packet = packet[0]
        #print packet

        validation_status, faulty_packet = validatePacket(packet)

        if validation_status:
            #IP header bytes
            ip_header = IP.unpackHeader(packet[0:20])
            if socket.inet_ntoa(ip_header[8]) == DESTINATION_IP and socket.inet_ntoa(ip_header[9]) == SOURCE_IP:
                #Get Length of IP header
                ip_ver = ip_header[0] >> 4
                ip_header_length = ip_header[0] & 0xF
                ip_length = ip_header_length * 4

                tcp_header = TCP.unpackHeader(packet[ip_length: ip_length + 20])
                ack = (tcp_header[5] & 0x10) >> 4
                syn = (tcp_header[5] & 0x02) >> 1

                if ack == 1 and syn == 1 and tcp_header[0] == DESTINATION_PORT and tcp_header[1] == SOURCE_PORT and tcp_header[3] == (ACK_NUM + 1):
                    #SYN-ACK received
                    SEQ_NUM = tcp_header[2] + 1
                    SEQ_START = tcp_header[2]
                    ACK_NUM = tcp_header[3]
                    packet_sent_time = time.time()

                    #ACKd
                    if CWND < SSTHRESH:
                        CWND += 1