Пример #1
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
Пример #2
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
Пример #3
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()
Пример #4
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))
Пример #5
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')
Пример #6
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)
Пример #7
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
Пример #8
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
Пример #9
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*

from TCP import *

servidor = TCP()

servidor.server('localhost', 45000)
Пример #10
0
 def __init__(self, game):
     self.tcp = TCP("127.0.0.1", "5005")
     self.game.players[0].set_connection(self.tcp)
Пример #11
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()
Пример #12
0
def analyses_toute_les_trames(Liste_trames, fichier):
    """list [ tuple(list[octects], bool, int ,int) ] -> None
    Analyse toutes les trames recuperees """

    length = len(Liste_trames)  # nombre de trames recuperees

    # Parcours de toutes les trames recuperees
    for i in range(length):

        Trame, ok, ligne_erreur, taille = Liste_trames[i]

        print("\n********************* Analyse de la trame", i + 1,
              "******************** \n")

        # if la trame est errone en raison des offsets invalides
        if Trame == []:
            print(
                " \nLa trame", i,
                "est erronee car l'offset n'est pas dans l'ordre croissant\n")
            fichier.write("*\n!\n")
            continue

        # if il manque des octets dans la trame
        if not ok:
            print("      \nLa trame", i, "a rencontré une erreur à la ligne ",
                  ligne_erreur, " de sa trame\n")
            fichier.write("*\n!\n")
            continue

        print(taille, " octets de donnees")

        # donne des noms differents a chaque trame et leurs composantes
        str_num = str(i)
        str_Ethernet = "Ethernet_" + str_num
        str_IP = "IP_" + str_num
        str_TCP = "TCP_" + str_num
        str_HTTP = "HTTP_" + str_num

        # Entete Ethernet
        dest_mac = Trame[:6]  # Destination (Adresse MAC)
        src_mac = Trame[6:12]  # Soruce (Adresse MAC)
        type_ethernet = Trame[12:14]  # Type Ethernet

        str_Ethernet = Ethernet(dest_mac, src_mac, type_ethernet)
        str_Ethernet.affichage()
        str_Ethernet.affichage_bouton(fichier)

        # If la trame n'est pas IPv4 then aller à la trame suivante
        if not est_IPv4(Trame):
            print("Notre analyseur ne prend pas en compte le protocole 0x" +
                  ''.join(Trame[12:14]))
            fichier.write("14 " + str(taille))
            continue

        # Entete IPv4
        version = Trame[14][0]  # Version
        header_length_ip = Trame[14][1]  # Header Length
        dsf = Trame[15]  # Differentiated Sevices Field
        total_length = Trame[16:18]  # Total Length
        id = Trame[18:20]  # Identification
        flags_ip = Trame[20]  # Flags
        offset = Trame[20:22]  # Framgment offset
        ttl = Trame[22]  # Time to live
        protocol = Trame[23]  # Protocol
        checksum_ip = Trame[24:26]  # Header Checksum
        src_ip = Trame[26:30]  # Source IP
        dest_ip = Trame[30:34]  # Destination IP
        options_ip = []  # Options IP

        str_IP = IP(version, header_length_ip, dsf, total_length, id, flags_ip,
                    offset, ttl, protocol, checksum_ip, src_ip, dest_ip,
                    options_ip)

        taille_options_IP = str_IP.taille_options_IP(
        )  # Recupere la taille des options IP si elles existent
        fin_IP = 34 + taille_options_IP  # Recupere le dernier octect de l'entete IP
        str_IP.set_options(Trame[34:fin_IP])  # Affectation des options de IP
        str_IP.verification_checksum(Trame[14:fin_IP])  # Check le checksum

        str_IP.affichage()
        str_IP.affichage_bouton(fichier)

        # if la trame recuperee n'est pas de la taille de totale_length
        if not nombre_octects_exacts(taille,
                                     int(''.join(str_IP.total_length), 16)):
            print("La trame contient ", taille,
                  "octets alors qu'elle devrait en contenir",
                  int(''.join(str_IP.total_length), 16) + 14)
            continue

        # if la trame n'est pas TCP then aller à la trame suivante
        if not est_TCP(Trame):
            print("\nNotre analyseur ne prend pas en compte le protocole 0x" +
                  ''.join(Trame[23]))
            fichier.write(str(fin_IP) + " " + str(taille) + "\n")
            continue

        # Entete TCP
        debut_TCP = fin_IP  # premier octer du segment TCP
        src_port = Trame[debut_TCP:debut_TCP + 2]  # Source Port
        dest_port = Trame[debut_TCP + 2:debut_TCP + 4]  # Destination Port
        sequence = Trame[debut_TCP + 4:debut_TCP + 8]  # Sequence number
        acknowledgment = Trame[debut_TCP + 8:debut_TCP +
                               12]  # acknowledgment number
        header_length_tcp = Trame[debut_TCP + 12]  # Header Length
        flags_tcp = Trame[debut_TCP + 12:debut_TCP + 14]  # Flags
        window = Trame[debut_TCP + 14:debut_TCP + 16]  # Window
        checksum_tcp = Trame[debut_TCP + 16:debut_TCP + 18]  # Checksum
        urgent_pointer = Trame[debut_TCP + 18:debut_TCP + 20]  # Urgent pointer
        options_tcp = []  # Options
        TCP_length = str(
            hex(
                int(''.join(str_IP.total_length), 16) - 20 -
                taille_options_IP)[2:].zfill(4))  # Taille du segment TCP

        str_TCP = TCP(src_port, dest_port, sequence, acknowledgment,
                      header_length_tcp, flags_tcp, window, checksum_tcp,
                      urgent_pointer, options_tcp)
        str_TCP.set_options(Trame[debut_TCP + 20:debut_TCP + 20 +
                                  str_TCP.taille_options_TCP()])
        str_TCP.verification_checksum(src_ip + dest_ip + ["00"] + [protocol] +
                                      [TCP_length[0:2]] + [TCP_length[2:4]] +
                                      Trame[debut_TCP:])  # Check le checksum
        str_TCP.affichage()
        str_TCP.affichage_bouton(fichier, debut_TCP)

        taille_options_TCP = str_TCP.taille_options_TCP(
        )  # Recupère la taille des options TCP si elles existent
        fin_TCP = debut_TCP + 20 + taille_options_TCP  # Recupere le dernier octect de l'entete IP

        # if pas de data then aller a la trame suivante
        if fin_TCP == taille:
            continue

        # if la trame n'est pas HTTP then aller à la trame suivante
        if not est_HTTP(Trame, src_port, dest_port):
            print(
                "\nNotre analyseur ne peut pas lire le contenu de ce segment (pas HTTP)"
            )
            continue

        debut_HTTP = fin_TCP  # Récupère le premier octet du segment HTTP
        str_HTTP = HTTP(Trame[debut_HTTP:])
        str_HTTP.affichage()
        str_HTTP.affichage_bouton(fichier, debut_HTTP)

    return None
Пример #13
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,
	)

	rospy.init_node("kayak_tcp")
	reader0 = KayakReader(0)
	reader1 = KayakReader(1)

	# Keeps requesting the most recent data
	if(tcp.mode=='client'):
		try:
			for i in range(15):
				print i, yaml.dump(tcp.request('glider-01'))
				#print i, tcp.request('glider-02')
		except:
			pass

	# Keeps providing the most recent data
	if(tcp.mode=='server'):
		counter = 0
		#k0 = dict(Temperature = reader0.temperature, Salinity = reader0.salinity, Latitude = reader0.latitude, Longitude = reader0.longitude, Depth = reader0.depth, x = reader0.x, y = reader0.y, z = reader0.z, w = reader0.w)
				
		try:
			while True:
				counter += 1

				tcp.database = {
					'glider-01': {
						'position': {
							'lat': -119.0,
							'lon': 34.0,
							'depth': 150.0,
						},
						'heading': {
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						},
						'science': {
							'temperature': 15.0,
							'salinity': 31.0,
							'oxygen': 4.5,
						},
					},
					'glider-02': {
						'position': {
							'lat': -119.0,
							'lon': 34.0,
							'depth': 150.0,
						},
						'heading': {
							'x': 0.0,
							'y': 0.0,
							'z': 0.0,
						},
						'science': {
							'temperature': 15.0,
							'salinity': 31.0,
							'oxygen': 4.5,
						},
					},
				}

				
		except:
			tcp.exit_server()
Пример #14
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from TCP import *

cliente = TCP()

conexao = cliente.conectar('localhost', 45000)
cliente.enviar_dados(conexao, (
    'In TCP, the congestion window is one of the factors that determines the number of bytes that can be outstanding at any time. The congestion window is maintained by the sender. Note that this is not to be confused with the sliding window size which is maintained by the receiver. The congestion window is a means of stopping a link between the sender and the receiver from becoming overloaded with too much traffic. It is calculated by estimating how much congestion there is on the link.When a connection is set up, the congestion window, a value maintained independently at each host, is set to a small multiple of the MSS allowed on that connection. Further variance in the congestion window is dictated by an AIMD approach. This means that if all segments are received and the acknowledgments reach the sender on time, some constant is added to the window size.'
) * 10)
cliente.fechar_conexao(conexao)