def client_receiver(data, address):
    server_log = open('server_log.txt', 'w+')
    print("Client {} Connected".format(address[1]))
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_port = new_port()
    server_new_address_port = ('localhost', server_port)
    server_socket.bind(server_new_address_port)
    state = states[1]
    last_sent_ack = None
    client_port = address[1]
    initial_sequence_number = 0
    ack_to_send = data.sequenceNumber+1
    packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, ack_to_send, 1, 1, 0, 1000).get()
    server_socket.sendto(packet, address)
    last_sent_ack = ack_to_send-1
    state = states[2]
    while state == states[2]:
        data, address = server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        if data.ackFlag and data.ackNumber == initial_sequence_number+1:
            state = states[3]
            ack_to_send, last_sent_ack = send_ack(server_socket, data, last_sent_ack, client_port, server_port, initial_sequence_number, address, ack_to_send)
    while state == states[3]:
        data, address = server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        print("Packet {} Received".format(data.sequenceNumber), file=server_log)
        ack_to_send, last_sent_ack = send_ack(server_socket, data, last_sent_ack, client_port, server_port, initial_sequence_number, address, ack_to_send)
        if data.finFlag:
            state = states[4]
    print("Connection Closed")
def close(receiver_thread):
    global state, states, server_ip, server_port, server_ip_port, client_port, udp_client_socket, establish_time, initial_sequence_number, last_acked, fin_recvd, last_received, last_sent, sent_time, fin_number, base, base_time, timeout, time_wait_start, time_two_msl
    while state != states[0]:
        if state == states[2]:
            packet = TCPHeader.TCPHeader(client_port, server_port, last_sent+1, 0, 0, 0, 1, 1500).get()
            last_sent += 1
            sent_time[str(last_sent)] = time.time()
            base = last_sent
            base_time = sent_time[str(last_sent)]
            udp_client_socket.sendto(packet, server_ip_port)
            state = states[3]
        elif state == states[3]:
            if last_acked == last_sent+1:
                fin_recvd = True
                receiver_thread.join()
                state = states[0]
            else:
                if time.time() - base_time > timeout:
                    packet = TCPHeader.TCPHeader(client_port, server_port, last_sent, 0, 0, 0, 1, 100).get()
                    sent_time[str(last_sent)] = time.time()
                    base = last_sent + 1
                    base_time = sent_time[str(last_sent)]
                    udp_client_socket.sendto(packet, server_ip_port)

    return True
def sender():
    global state, states, server_ip, server_port, server_ip_port, client_port, udp_client_socket, establish_time, initial_sequence_number, window, last_sent, last_sent_time, base, base_time, last_received
    while not done:
        dif_time = time.time() - base_time
        if dif_time > timeout:
            print(dif_time, timeout)
            if base not in dropped:
                dropped.append(base)
                print("Packet {} Dropped".format(base), file=client_log)
            window = max(window//2, 1)
            last_sent = base - 1
            packet = TCPHeader.TCPHeader(client_port, server_port, last_sent + 1, last_received + 1, 1, 0, 0, 1000).get()
            udp_client_socket.sendto(packet, server_ip_port)
            last_sent_time = time.time()
            last_sent += 1
            base_time = last_sent_time
        else:
            if last_acked - 1 + window > last_sent and time.time() - last_sent_time > 0.1:
                if last_sent+1 in dropped:
                    dropped.remove(last_sent+1)
                packet = TCPHeader.TCPHeader(client_port, server_port, last_sent + 1, last_received + 1, 1, 0, 0, 1000).get()
                udp_client_socket.sendto(packet, server_ip_port)
                last_sent_time = time.time()
                sent_time[str(last_sent + 1)] = last_sent_time
                last_sent += 1
    return
Пример #4
0
    def getTCPHeader(self, localhostIP, destinationIP, user_request):
        tcpheader_obj = TCPHeader()
        tcpheader_obj.setValues(self.sourcePortNum, self.destinationPortNum, self.seq_num, self.current_ack_no, 0, 1, 0, user_request)

        tcp_header = tcpheader_obj.build(localhostIP, destinationIP)

        return tcp_header
Пример #5
0
    def getTCPHeader(self, localhostIP, destinationIP, user_request):
        tcpheader_obj = TCPHeader()
        tcpheader_obj.setValues(
            self.sourcePortNum, self.destinationPortNum, self.seq_num, self.current_ack_no, 0, 1, 0, user_request
        )

        tcp_header = tcpheader_obj.build(localhostIP, destinationIP)

        return tcp_header
Пример #6
0
    def sendAckToServer(self, local_current_ack_no, localhostIP, destinationIP, sendSock):

        self.ip_packet_ID = self.ip_packet_ID + 1
        ipheader = self.getIPHeader(localhostIP, destinationIP, self.ip_packet_ID)

        tcpobj = TCPHeader()
        tcpobj.setValues(self.sourcePortNum, self.destinationPortNum, self.seq_num, local_current_ack_no, 0, 1, 0, "")
        tcpheader = tcpobj.build(localhostIP, destinationIP)

        packet = ipheader + tcpheader + ""

        sendSock.sendto(packet, (destinationIP, self.destinationPortNum))
Пример #7
0
    def sendAckToServer(self, local_current_ack_no, localhostIP, destinationIP, sendSock):

        self.ip_packet_ID = self.ip_packet_ID + 1
        ipheader = self.getIPHeader(localhostIP, destinationIP, self.ip_packet_ID)

        tcpobj = TCPHeader()
        tcpobj.setValues(self.sourcePortNum, self.destinationPortNum, self.seq_num, local_current_ack_no, 0, 1, 0, "")
        tcpheader = tcpobj.build(localhostIP, destinationIP)

        packet = ipheader + tcpheader + ""

        sendSock.sendto(packet, (destinationIP, self.destinationPortNum))
Пример #8
0
    def receiveSYNACKPacket(self, sendSock, SYNPacket, localhostIP, destinationIP):
        self.ack_packet = ""
        self.cwnd = 1
        self.startTime = 0
        user_request = ""

        receiveSock = self.getReceiveRawSocket()
        self.startTime = time.clock()

        # Receives packet
        while True:
            receiveSock.settimeout(180)
            try:
                receivedPacket = receiveSock.recvfrom(65565)
            except:
                print "Exception in receiving SYN/ACK packet"
                sendSock.close()
                receiveSock.close()
                sys.exit(2)

            packet = receivedPacket[0]

            received_IPHeader = packet[0:20]
            ipheader = IPHeader(0, 0, 0)
            ipheader.extract(received_IPHeader)

            checksum = self.calculateCheckSum(received_IPHeader)

            time_elapsed = time.clock() - self.startTime

            if time_elapsed > 60:

                sendSock.sendto(SYNPacket, (destinationIP, self.destinationPortNum))
                self.startTime = time.clock()

            if (ipheader.protocol == 6) and (checksum == 0) and (ipheader.sourceIP == destinationIP) and (ipheader.destinationIP == localhostIP):
                get_TCPHeader = self.getTCPHeaderFromIPHeader(packet, ipheader)
                tcpheader = TCPHeader()
                tcpheader.extract(get_TCPHeader)

                if (tcpheader.sourcePort == self.destinationPortNum and tcpheader.destPort == self.sourcePortNum and tcpheader.ack_flg == 1 and tcpheader.ackNo == self.seq_num + 1 and not tcpheader.rst_flg):
                    self.seq_num = tcpheader.ackNo
                    self.current_ack_no = tcpheader.sequenceNo + 1
                    self.ip_packet_ID = self.ip_packet_ID + 1
                    ipheader1 = self.getIPHeader(localhostIP, destinationIP, self.ip_packet_ID)
                    user_request = self.getHttpGETRequest(self.url, self.urlHostName)

                    tcp_header1 = self.getTCPHeader(localhostIP, destinationIP, user_request)
                    self.ack_packet = ipheader1 + tcp_header1 + user_request
                    sendSock.sendto(self.ack_packet, (destinationIP, 80))
                    break
        # Handshake Completed, start downloading file from the server
        self.getMessagesFromServer(time.clock(), user_request, localhostIP, destinationIP, sendSock, receiveSock)
Пример #9
0
    def buildSYNPacket(self, localhostIP, destinationIP):

        IPHeaderObj = IPHeader(localhostIP, destinationIP, self.ip_packet_ID)
        ipHeader = IPHeaderObj.build()
        userData = ""

        TCPObj = TCPHeader()

        #Set the SYN Flag
        TCPObj.setValues(self.sourcePortNum, self.destinationPortNum, self.seq_num, self.current_ack_no, 1, 0, 0, userData)
        tcpHeader = TCPObj.build(localhostIP, destinationIP)

        SYNPacket = ipHeader + tcpHeader + userData
        return SYNPacket
def send_ack(server_socket, data, last_sent_ack, client_port, server_port, initial_sequence_number, address, ack_to_send):
    if data.sequenceNumber == last_sent_ack + 1:
        ack_to_send = data.sequenceNumber + 1
        packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, ack_to_send, 1, 0, 0,
                                     1000).get()
        # print("Sent ack {}".format(ack_to_send))
        server_socket.sendto(packet, address)
        last_sent_ack += 1
    else:
        ack_to_send = last_sent_ack + 1
        packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, ack_to_send, 1, 0, 0,
                                     1000).get()
        server_socket.sendto(packet, address)
    return ack_to_send, last_sent_ack
def receiver():
    global state, states, server_ip, server_port, server_ip_port, client_port, udp_client_socket, establish_time, initial_sequence_number, last_acked, fin_recvd, last_received, base_time, base, window, alpha, beta, dev_rtt, estimated_rtt, timeout, dropped, fin_number, sample_log, window_log
    while not fin_recvd:
        try:
            received_packet, address = udp_client_socket.recvfrom(20)
        except:
            continue
        received_tcp = TCPHeader.make_tcp_from_bytes(received_packet)
        if received_tcp.ackFlag:
            if received_tcp.ackNumber > last_acked:
                window = min(window + (received_tcp.ackNumber - last_acked), 20)
                for i in range(last_acked, received_tcp.ackNumber):
                    if i not in dropped:
                        sent_time_set = False
                        while not sent_time_set:
                            try:
                                sample = time.time() - sent_time[str(i)]
                                sent_time_set = True
                            except KeyError:
                                sent_time_set = False
                        print(sample, file=sample_log)
                        estimated_rtt = (1-alpha) * estimated_rtt + alpha*sample
                        dev_rtt = (1 - beta) * dev_rtt + beta*(abs(sample - estimated_rtt))
                        timeout = estimated_rtt + 4 * dev_rtt
                # print("Timeout = {}".format(timeout))
                # print("Window = {}".format(window))
            last_acked = received_tcp.ackNumber
            if received_tcp.ackNumber > base:
                base_time = time.time()
                base = received_tcp.ackNumber
        if received_tcp.sequenceNumber == last_received+1 or last_received is None:
            last_received = received_tcp.sequenceNumber
    return
Пример #12
0
    def buildSYNPacket(self, localhostIP, destinationIP):

        IPHeaderObj = IPHeader(localhostIP, destinationIP, self.ip_packet_ID)
        ipHeader = IPHeaderObj.build()
        userData = ""

        TCPObj = TCPHeader()

        # Set the SYN Flag
        TCPObj.setValues(
            self.sourcePortNum, self.destinationPortNum, self.seq_num, self.current_ack_no, 1, 0, 0, userData
        )
        tcpHeader = TCPObj.build(localhostIP, destinationIP)

        SYNPacket = ipHeader + tcpHeader + userData
        return SYNPacket
def handshake():
    global state, states, server_ip, server_port, server_ip_port, client_port, udp_client_socket, establish_time, initial_sequence_number, last_acked, last_sent, base_time, base, last_sent_time, last_sent, last_received
    while state != states[2]:
        if state == states[0]:
            initial_sequence_number = 1
            expected_ack = initial_sequence_number + 1
            packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, 0, 0, 1, 0, 1000).get()
            udp_client_socket.sendto(packet, server_ip_port)
            last_sent = initial_sequence_number
            sent_time[str(last_sent)] = time.time()
            last_sent_time = sent_time[str(last_sent)]
            base = initial_sequence_number
            base_time = last_sent_time
            state = states[1]
        elif state == states[1]:
            if time.time() - base_time > timeout:
                packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, 0, 0, 1, 0, 1000).get()
                udp_client_socket.sendto(packet, server_ip_port)
                last_sent = initial_sequence_number
                sent_time[str(last_sent)] = time.time()
                last_sent_time = sent_time[str(last_sent)]
                base = initial_sequence_number
                base_time = last_sent_time
                continue
            try:
                received_packet, address = udp_client_socket.recvfrom(20)
            except:
                continue
            server_port = address[1]
            server_ip = address[0]
            server_ip_port = (server_ip, server_port)
            received_tcp = TCPHeader.make_tcp_from_bytes(received_packet)
            if received_tcp.ackFlag and received_tcp.ackNumber == expected_ack and received_tcp.synFlag:
                last_acked = expected_ack
                establish_time = time.time()
                last_received = received_tcp.sequenceNumber
                ack_to_send = received_tcp.sequenceNumber + 1
                packet = TCPHeader.TCPHeader(client_port, server_port, expected_ack, ack_to_send, 1, 0, 0, 1000).get()
                initial_sequence_number = expected_ack
                last_sent = expected_ack
                sent_time[str(expected_ack)] = time.time()
                udp_client_socket.sendto(packet, server_ip_port)
                base = last_sent
                base_time = sent_time[str(expected_ack)]
                state = states[2]
    return True
def main_receiver():
    global main_server_socket
    while True:
        data, address = main_server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        if data.synFlag:
            test_file = open('test.txt', 'w+')
            thread = threading.Thread(target=client_receiver, args=(data, address))
            thread.start()
def main_receiver():
    global main_server_socket
    while True:
        data, address = main_server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        if data.synFlag:
            print("Received in main receiver", data)
            thread = threading.Thread(target=client_receiver,
                                      args=(data, address))
            thread.start()
Пример #16
0
    def startTearDown(self, local_current_ack_no, localhostIP, destinationIP, sendSock, receiveSock):
        # Sends ACK to server of the received packet content
        self.sendAckToServer(local_current_ack_no, localhostIP, destinationIP, sendSock)

        self.ip_packet_ID = self.ip_packet_ID + 1
        ipheader = self.getIPHeader(localhostIP, destinationIP, self.ip_packet_ID)

        tcpobj = TCPHeader()
        tcpobj.setValues(self.sourcePortNum, self.destinationPortNum, self.seq_num, local_current_ack_no, 0, 1, 1, "")
        tcpheader = tcpobj.build(localhostIP, destinationIP)

        packet = ipheader + tcpheader + ""

        sendSock.sendto(packet, (destinationIP, 80))
        start_time = time.clock()

        while True:
            try:
                receivedPacket = receiveSock.recvfrom(65565)
            except:
                print "Exception in tear down"
                sys.exit(2)

            packetData = receivedPacket[0]

            received_IPHeader = packetData[0:20]
            ipheader = IPHeader(0, 0, 0)
            ipheader.extract(received_IPHeader)

            checksum = self.calculateCheckSum(received_IPHeader)

            spent_Time = time.clock() - start_time

            # Resend if time exceeds 1min
            if spent_Time > 60:
                sendSock.sendto(packet, (destinationIP, 80))
                start_time = time.clock()
            # Checks if the protocol is 6, and checks the source and destination in the IP Packet
            if (
                ipheader.protocol == 6
                and ipheader.sourceIP == destinationIP
                and ipheader.destinationIP == localhostIP
                and checksum == 0
            ):
                get_TCPHeader = self.getTCPHeaderFromIPHeader(packetData, ipheader)
                tcpheader = TCPHeader()
                tcpheader.extract(get_TCPHeader)

                if (
                    tcpheader.sourcePort == self.destinationPortNum
                    and tcpheader.destPort == self.sourcePortNum
                    and tcpheader.ackNo == self.seq_num + 1
                ):
                    return
def send_ack(server_socket, data, last_sent_ack, client_port, server_port,
             initial_sequence_number, address, ack_to_send):
    # if data.sequenceNumber == last_sent_ack + 1:
    #     ack_to_send = data.sequenceNumber + 1
    #     packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, ack_to_send, 1, 0, 0,
    #                                  1000).get()
    #     server_socket.sendto(packet, address)
    #     last_sent_ack += 1
    # else:
    #     ack_to_send = last_sent_ack + 1
    #     packet = TCPHeader.TCPHeader(client_port, server_port, initial_sequence_number, ack_to_send, 1, 0, 0,
    #                                  1000).get()
    #     server_socket.sendto(packet, address)

    packet = TCPHeader.TCPHeader(client_port, server_port,
                                 initial_sequence_number,
                                 data.sequenceNumber + 1, 1, 0, 0, 1000).get()
    server_socket.sendto(packet, address)

    return ack_to_send, last_sent_ack
Пример #18
0
    def getMessagesFromServer(self, start_Time, user_request, localhostIP, destinationIP, sendSock, receiveSock):

        self.page_content_dict = {}

        roundTripTime = time.clock()

        http_ack_flg = False
        self.seq_num = self.seq_num + len(user_request)

        while True:
            receiveSock.settimeout(180)
            try:
                receivedPacket = receiveSock.recvfrom(65565)
            except receiveSock.timeout:
                print "Socket timed out. No packet received in 3 minutes"
                sendSock.close()
                receiveSock.close()
                sys.exit(2)

            spent_Time = time.clock() - start_Time
            # Resend if the packet is not received before 1min
            if spent_Time > 60 and not http_ack_flg:

                sendSock.sendto(self.ack_packet, (destinationIP, 80))
                start_Time = time.clock()

            packet = receivedPacket[0]
            received_IPHeader = packet[0:20]
            ipheader = IPHeader(0, 0, 0)
            ipheader.extract(received_IPHeader)

            checksum = self.calculateCheckSum(received_IPHeader)
            # Checks if the protocol is TCP, if the server IP is the source IP in the packet, if the localhostIP is the destination in the packet
            if ipheader.protocol == 6 and ipheader.sourceIP == destinationIP and ipheader.destinationIP == localhostIP and checksum == 0:

                get_TCPHeader = self.getTCPHeaderFromIPHeader(packet, ipheader)
                tcpheader = TCPHeader()
                tcpheader.extract(get_TCPHeader)

                # Strip of header length, and gets the actual data
                header_length = (tcpheader.HL_Offset * 4) + (ipheader.ihl * 4)
                message_length = ipheader.totalLength - header_length
                actual_page_content = packet[header_length:]

                self.checkcwnd(tcpheader)

                # Checks valid sourcePort,destPort in TCP header
                if tcpheader.sourcePort == self.destinationPortNum and tcpheader.destPort == self.sourcePortNum and tcpheader.ackNo == self.seq_num:
                    time_spent = time.clock() - roundTripTime

                    if (time_spent > 180):
                        print "No packet received from server for 3 minutes. Terminating program. "
                        sendSock.close()
                        receiveSock.close()
                        sys.exit(2)

                    roundTripTime = time.clock()
                    # Indicates end of data
                    if tcpheader.fin_flg == 1:
                        self.current_ack_no += 1
                        self.page_content_dict[tcpheader.sequenceNo] = actual_page_content
                        self.startTearDown(self.current_ack_no, localhostIP, destinationIP, sendSock, receiveSock)
                        break
                    # Continue to receive data, indicates this is an ACK
                    if tcpheader.ack_flg == 1 and http_ack_flg == False and tcpheader.ackNo == self.seq_num:
                        http_ack_flg = True
                        continue
                    if tcpheader.syn_flg == 1 and tcpheader.ack_flg == 1:
                        continue
                    else:
                        # Stores Data in the dictionary in sequenceNo:data format
                        if self.page_content_dict.has_key(tcpheader.sequenceNo):
                            self.sendAckToServer(message_length + tcpheader.sequenceNo, localhostIP, destinationIP, sendSock)
                        else:
                            self.current_ack_no = self.current_ack_no + message_length
                            self.page_content_dict[tcpheader.sequenceNo] = actual_page_content
                            self.sendAckToServer(self.current_ack_no, localhostIP, destinationIP, sendSock)
def client_receiver(data, address):
    pprint(vars(data))
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_port = new_port()
    server_new_address_port = ('localhost', server_port)
    server_socket.bind(server_new_address_port)
    state = states[1]
    last_sent_ack = None
    client_port = address[1]
    initial_sequence_number = 0
    ack_to_send = data.sequenceNumber + 1
    packet = TCPHeader.TCPHeader(client_port, server_port,
                                 initial_sequence_number, ack_to_send, 1, 1, 0,
                                 1000).get()
    server_socket.sendto(packet, address)
    last_sent_ack = ack_to_send - 1
    state = states[2]
    tmp = 2
    while state == states[2]:
        data, address = server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        if data.ackFlag and data.ackNumber == initial_sequence_number + 1:
            state = states[3]
            ack_to_send, last_sent_ack = send_ack(server_socket, data,
                                                  last_sent_ack, client_port,
                                                  server_port,
                                                  initial_sequence_number,
                                                  address, ack_to_send)
    fin_time = 0
    print("Y")
    # tmp = 2
    while state == states[3] or (state == states[4]
                                 and time.time() - fin_time < 1):
        # print(state, fin_time, time.time())
        # print("Z")
        data, address = server_socket.recvfrom(20)
        # print("P")
        data = TCPHeader.make_tcp_from_bytes(data)
        # if tmp == 1:
        #     pprint(vars(data))
        # if data.finFlag and tmp > 0:
        #     print("HOOOOOOOOOY", tmp)
        #     print("aCKK tO sEnD", ack_to_send)
        #     tmp -= 1
        #     continue
        ack_to_send, last_sent_ack = send_ack(server_socket, data,
                                              last_sent_ack, client_port,
                                              server_port,
                                              initial_sequence_number, address,
                                              ack_to_send)
        if data.finFlag and state != states[4]:
            # print("W")
            state = states[4]
            fin_time = time.time()

    print("X")
    tmp = 2
    state = states[5]
    initial_sequence_number += 1
    packet = TCPHeader.TCPHeader(client_port, server_port,
                                 initial_sequence_number, ack_to_send, 0, 0, 1,
                                 1000).get()
    server_socket.sendto(packet, address)
    print(initial_sequence_number + 1)
    while state == states[5]:
        data, address = server_socket.recvfrom(20)
        data = TCPHeader.make_tcp_from_bytes(data)
        print("S")
        if data.ackFlag and data.ackNumber == initial_sequence_number + 1:
            if tmp > 2:
                tmp -= 1
                continue
            state = states[6]
            print("Done")
Пример #20
0
    def getMessagesFromServer(self, start_Time, user_request, localhostIP, destinationIP, sendSock, receiveSock):

        self.page_content_dict = {}

        roundTripTime = time.clock()

        http_ack_flg = False
        self.seq_num = self.seq_num + len(user_request)

        while True:
            receiveSock.settimeout(180)
            try:
                receivedPacket = receiveSock.recvfrom(65565)
            except receiveSock.timeout:
                print "Socket timed out. No packet received in 3 minutes"
                sendSock.close()
                receiveSock.close()
                sys.exit(2)

            spent_Time = time.clock() - start_Time
            # Resend if the packet is not received before 1min
            if spent_Time > 60 and not http_ack_flg:

                sendSock.sendto(self.ack_packet, (destinationIP, 80))
                start_Time = time.clock()

            packet = receivedPacket[0]
            received_IPHeader = packet[0:20]
            ipheader = IPHeader(0, 0, 0)
            ipheader.extract(received_IPHeader)

            checksum = self.calculateCheckSum(received_IPHeader)
            # Checks if the protocol is TCP, if the server IP is the source IP in the packet, if the localhostIP is the destination in the packet
            if (
                ipheader.protocol == 6
                and ipheader.sourceIP == destinationIP
                and ipheader.destinationIP == localhostIP
                and checksum == 0
            ):

                get_TCPHeader = self.getTCPHeaderFromIPHeader(packet, ipheader)
                tcpheader = TCPHeader()
                tcpheader.extract(get_TCPHeader)

                # Strip of header length, and gets the actual data
                header_length = (tcpheader.HL_Offset * 4) + (ipheader.ihl * 4)
                message_length = ipheader.totalLength - header_length
                actual_page_content = packet[header_length:]

                self.checkcwnd(tcpheader)

                # Checks valid sourcePort,destPort in TCP header
                if (
                    tcpheader.sourcePort == self.destinationPortNum
                    and tcpheader.destPort == self.sourcePortNum
                    and tcpheader.ackNo == self.seq_num
                ):
                    time_spent = time.clock() - roundTripTime

                    if time_spent > 180:
                        print "No packet received from server for 3 minutes. Terminating program. "
                        sendSock.close()
                        receiveSock.close()
                        sys.exit(2)

                    roundTripTime = time.clock()
                    # Indicates end of data
                    if tcpheader.fin_flg == 1:
                        self.current_ack_no += 1
                        self.page_content_dict[tcpheader.sequenceNo] = actual_page_content
                        self.startTearDown(self.current_ack_no, localhostIP, destinationIP, sendSock, receiveSock)
                        break
                    # Continue to receive data, indicates this is an ACK
                    if tcpheader.ack_flg == 1 and http_ack_flg == False and tcpheader.ackNo == self.seq_num:
                        http_ack_flg = True
                        continue
                    if tcpheader.syn_flg == 1 and tcpheader.ack_flg == 1:
                        continue
                    else:
                        # Stores Data in the dictionary in sequenceNo:data format
                        if self.page_content_dict.has_key(tcpheader.sequenceNo):
                            self.sendAckToServer(
                                message_length + tcpheader.sequenceNo, localhostIP, destinationIP, sendSock
                            )
                        else:
                            self.current_ack_no = self.current_ack_no + message_length
                            self.page_content_dict[tcpheader.sequenceNo] = actual_page_content
                            self.sendAckToServer(self.current_ack_no, localhostIP, destinationIP, sendSock)
Пример #21
0
    def receiveSYNACKPacket(self, sendSock, SYNPacket, localhostIP, destinationIP):
        self.ack_packet = ""
        self.cwnd = 1
        self.startTime = 0
        user_request = ""

        receiveSock = self.getReceiveRawSocket()
        self.startTime = time.clock()

        # Receives packet
        while True:
            receiveSock.settimeout(180)
            try:
                receivedPacket = receiveSock.recvfrom(65565)
            except:
                print "Exception in receiving SYN/ACK packet"
                sendSock.close()
                receiveSock.close()
                sys.exit(2)

            packet = receivedPacket[0]

            received_IPHeader = packet[0:20]
            ipheader = IPHeader(0, 0, 0)
            ipheader.extract(received_IPHeader)

            checksum = self.calculateCheckSum(received_IPHeader)

            time_elapsed = time.clock() - self.startTime

            if time_elapsed > 60:

                sendSock.sendto(SYNPacket, (destinationIP, self.destinationPortNum))
                self.startTime = time.clock()

            if (
                (ipheader.protocol == 6)
                and (checksum == 0)
                and (ipheader.sourceIP == destinationIP)
                and (ipheader.destinationIP == localhostIP)
            ):
                get_TCPHeader = self.getTCPHeaderFromIPHeader(packet, ipheader)
                tcpheader = TCPHeader()
                tcpheader.extract(get_TCPHeader)

                if (
                    tcpheader.sourcePort == self.destinationPortNum
                    and tcpheader.destPort == self.sourcePortNum
                    and tcpheader.ack_flg == 1
                    and tcpheader.ackNo == self.seq_num + 1
                    and not tcpheader.rst_flg
                ):
                    self.seq_num = tcpheader.ackNo
                    self.current_ack_no = tcpheader.sequenceNo + 1
                    self.ip_packet_ID = self.ip_packet_ID + 1
                    ipheader1 = self.getIPHeader(localhostIP, destinationIP, self.ip_packet_ID)
                    user_request = self.getHttpGETRequest(self.url, self.urlHostName)

                    tcp_header1 = self.getTCPHeader(localhostIP, destinationIP, user_request)
                    self.ack_packet = ipheader1 + tcp_header1 + user_request
                    sendSock.sendto(self.ack_packet, (destinationIP, 80))
                    break
        # Handshake Completed, start downloading file from the server
        self.getMessagesFromServer(time.clock(), user_request, localhostIP, destinationIP, sendSock, receiveSock)