def listen(self, gateway, address):
        size = BUFFER_SIZE
        while True:
            try:
                packet = gateway.recv(size)
                if packet:
                    unpacked = packet_utils.unpack(packet)
                    client_sequence_num = unpacked.sequence_number
                    source_ip = unpacked.source_ip
                    source_port = unpacked.source_port
                    data = unpacked.data

                    client_id = source_port
                    destination_ip = source_ip
                    destination_port = source_port

                    if client_id not in self.client_dict:
                        self.client_dict[client_id] = 0

                    expected_sequence_number = self.client_dict[client_id]

                    sequence_number = self.sequence_number
                    if client_sequence_num == expected_sequence_number:
                        # 1 in 500 chance to 'drop' the received packet
                        if randint(1, 500) > 1:
                            print(data)
                            self.client_dict[client_id] += 1
                            if self.client_dict[
                                    client_id] > MAX_SEQUENCE_NUMBER:
                                self.client_dict[client_id] = 0
                            next_sequence_number = self.client_dict[client_id]
                            response_packet = packet_utils.create_packet(
                                sequence_number, IP, PORT, destination_ip,
                                destination_port,
                                bytes(str(next_sequence_number), "utf-8"))
                        else:
                            response_packet = packet_utils.create_packet(
                                sequence_number, IP, PORT, destination_ip,
                                destination_port,
                                bytes(str(expected_sequence_number), "utf-8"))
                    else:
                        response_packet = packet_utils.create_packet(
                            sequence_number, IP, PORT, destination_ip,
                            destination_port,
                            bytes(str(expected_sequence_number), "utf-8"))
                    gateway.sendall(response_packet)
                    gateway.close()
                    self.sequence_number += 1
                    if self.sequence_number > MAX_SEQUENCE_NUMBER:
                        self.sequence_number = 0
                else:
                    gateway.close()
            except:
                gateway.close()
                return
Example #2
0
    def __init__(self, r_number, sock_addresses, neighbours):
        self.r_number = r_number
        self.sock_addresses = sock_addresses

        self.sockets = []
        for i in range(len(sock_addresses)):
            self.sockets.append(socket.socket(socket.AF_INET, socket.SOCK_DGRAM))
            self.sockets[i].bind((sock_addresses[i][0], sock_addresses[i][1]))

        self.neighbours = {}
        self.neighbour_nodes = {}
        self.destinations = {}

        for neighbour in neighbours:
            self.neighbours[str(neighbour[0])] = neighbour[1]
            self.neighbour_nodes[str(neighbour[0])] = (neighbour[2][0], neighbour[2][1])

        # send configuration information to the controller
        neighbours_string = str(r_number) + ","
        for n in neighbours:
            neighbours_string += str(n[0]) + ","
        neighbours_string = bytes(neighbours_string[:-1], "utf-8")
        packet = packet_utils.create_packet(0, PACKET_TYPE_HELLO, self.sock_addresses[0][0], self.sock_addresses[0][1],
                                            CONTROLLER_IP, CONTROLLER_PORT, neighbours_string)
        self.sockets[0].sendto(packet, (CONTROLLER_IP, CONTROLLER_PORT))

        n = 0
        for sock in self.sockets:
            t = threading.Thread(target=self.receive_messages, args=(n, sock))
            t.setDaemon(True)
            t.start()
            n += 1
Example #3
0
 def send_request(self, source_client, destination_client):
     """
     Takes a source and destination client and queries the controller for route information
     """
     route = bytes(source_client + "-" + destination_client, "utf-8")
     packet = packet_utils.create_packet(0, PACKET_TYPE_LINK_STATE_REQUEST, self.sock_addresses[0][0],
                                         self.sock_addresses[0][1], CONTROLLER_IP, CONTROLLER_PORT, route)
     self.sockets[0].sendto(packet, (CONTROLLER_IP, CONTROLLER_PORT))
Example #4
0
    def communicate(self):
        while self.connected:
            try:
                server_port = 50003

                if server_port not in self.server_dict:
                    self.server_dict[server_port] = 0
                else:
                    self.server_dict[server_port] += 1
                    if self.server_dict[server_port] > MAX_SEQUENCE_NUMBER:
                        self.server_dict[server_port] = 0

                sequence_number = self.server_dict[server_port]

                message = bytes(str(sequence_number), "utf-8")

                server_packet = packet_utils.create_packet(sequence_number, IP, 0, SERVER_IP, server_port, message)
                gateway_packet = packet_utils.create_packet(sequence_number, IP, 0, GATEWAY_IP, GATEWAY_PORT,
                                                            server_packet)
                acknowledged = False

                while not acknowledged:
                    self.sock.sendall(gateway_packet)
                    try:
                        ready = select([self.sock], [], [], RETRY_TIMEOUT)
                        if ready[0]:
                            response_packet = self.sock.recv(BUFFER_SIZE)
                            unpacked = packet_utils.unpack(bytes(response_packet))
                            expected_next_sequence_number = unpacked.data
                            if int(expected_next_sequence_number) == int(sequence_number):
                                acknowledged = False
                                print("resending {}...".format(sequence_number))
                            else:
                                acknowledged = True
                    except ConnectionAbortedError:
                        print("Your connection has timed out, please restart the program.")
                        input("Press enter to quit")
                        break

            except ConnectionResetError:
                print("Your connection to the gateway has been lost, please restart the program.")
                input("Press enter to quit")
                break
    def listen(self):
        while True:
            packet, address = self.sock.recvfrom(BUFFER_SIZE)
            unpacked = packet_utils.unpack(packet)
            packet_type = unpacked.packet_type

            # router initialisation information
            if packet_type == PACKET_TYPE_HELLO:
                self.stable = False
                neighbour_info = unpacked.data.split(",")
                r_number = neighbour_info[0]
                r_ip = unpacked.source_ip
                r_port = unpacked.source_port
                self.router_addresses[r_number] = (r_ip, r_port)

                self.vertices.append(r_number)
                self.edges[neighbour_info[0]] = {}
                for i in range(1, len(neighbour_info)):
                    self.edges[neighbour_info[0]][neighbour_info[i]] = 1
                    # assume any non-ints are clients, catch clients and add them to list
                    try:
                        int(neighbour_info[i])
                    except ValueError:
                        self.client_list.append(neighbour_info[i])
                        self.vertices.append(neighbour_info[i])
                        self.edges[neighbour_info[i]] = {r_number: 1}

            # route requests from routers
            if packet_type == PACKET_TYPE_LINK_STATE_REQUEST:
                route = unpacked.data
                if route in self.route_table:
                    router_path = self.route_table[route]
                else:
                    # reverse the route order and check again, return route in reverse
                    route = route[-2:] + "-" + route[:2]
                    if route in self.route_table:
                        router_path = self.route_table[route][::-1]
                    route = route[-2:] + "-" + route[:2]

                print("\nController sending route information...")
                print("{}: {}\n".format(route, router_path))
                for i in range(len(router_path) - 1):
                    r_ip = self.router_addresses[str(router_path[i])][0]
                    r_port = self.router_addresses[str(router_path[i])][1]
                    target_router = str(router_path[i + 1])
                    destination = route[-2:]
                    info = bytes(destination + target_router, "utf-8")
                    packet = packet_utils.create_packet(0, PACKET_TYPE_LINK_STATE_UPDATE, CONTROLLER_IP,
                                                        CONTROLLER_PORT, r_ip, r_port, info)
                    self.sock.sendto(packet, (r_ip, r_port))
Example #6
0
    def send_messages(self):
        while True:
            message_out = bytes(input(""), "utf-8")

            have_client = False
            while not have_client:
                destination = input("Select a Client by entering a number:\nBill[1], Carl[2], Dave[3], Eoin[4]:\n")
                dest_client = 'E' + destination
                if dest_client not in clients or dest_client == 'E0':
                    print("Error, try again.\n")
                else:
                    have_client = True

            packet = packet_utils.create_packet(0, PACKET_TYPE_CLIENT_MSG, self.host, self.port,
                                                clients[dest_client][0], clients[dest_client][1], message_out)
            self.sock.sendto(packet, self.router_address)
Example #7
0
    def listen(self, client, address):
        size = BUFFER_SIZE
        while True:
            try:
                packet = client.recv(size)
                if packet:
                    print("RECEIVED PACKET FROM {}:{}".format(address[0], address[1]))
                    unpacked = packet_utils.unpack(packet)
                    client_packet = packet_utils.unpack(bytes(unpacked.data, "utf-8"))

                    sequence_number = client_packet.sequence_number
                    source_ip = address[0]
                    source_port = address[1]
                    destination_ip = client_packet.destination_ip
                    destination_port = client_packet.destination_port
                    data = bytes(client_packet.data, "utf-8")

                    print("DESTINATION: {}:{}".format(destination_ip, destination_port))
                    print("SEQUENCE NO.: {}".format(sequence_number))

                    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                    try:
                        server_sock.connect((destination_ip, destination_port))
                    except ConnectionRefusedError:
                        print('ERROR: The connection was refused, is the server running?')
                        input("Press enter to quit")

                    server_packet = packet_utils.create_packet(sequence_number, source_ip, source_port, destination_ip,
                                                               destination_port, data)
                    packet_utils.to_string(server_packet)
                    print("forwarding to server...\n")
                    server_sock.sendall(server_packet)

                    server_response = server_sock.recv(BUFFER_SIZE)
                    unpacked = packet_utils.unpack(server_response)
                    data = unpacked.data
                    print("SERVER RESPONSE: {}\n".format(data))
                    client.sendall(server_response)
                else:
                    client.close()
            except:
                client.close()
                return