コード例 #1
0
def create_cache(records_file_name):
    cache = Cache()
    records_table = open(records_file_name, "r")
    for line in records_table:
        cache.add_static_record(Record.from_json(line))
    records_table.close()
    return cache
コード例 #2
0
    def resolver_function(self, record, query, query_sender_info):
        while True:
            ip, port = split(":", record.value)
            data = open_connection(ip, int(port), query)
            args = data.split("+")

            if args[0] is "%":
                if args[1] == "Not found":  # case the record didnt found sent - "Not found".
                    self.socket.sendto("Not found", query_sender_info)
                    return
                else:
                    # add glue records to the cache and keep searching.
                    record = Record.from_json(args[1])
                    self.cache.add_dynamic_record(record)
                    record = Record.from_json(args[2])
                    self.cache.add_dynamic_record(record)
                    continue

            elif args[0] is "$": # found the record -  send to the client.
                self.cache.add_dynamic_record(Record.from_json(args[1]))
                self.socket.sendto(data, query_sender_info)
                return
コード例 #3
0
def main():
    # initialize the socket.
    socket_info = sys.argv[1]
    local_server_ip, port = socket_info.split(":")
    port = int(port)
    s = socket(AF_INET, SOCK_DGRAM)
    # create cache
    cache = Cache()
    cache.start_timer(4)

    # start reading query and send them to the local server.
    while True:
        query = raw_input("Enter query: ")
        if query == "stop":
            break

        _, domain_name, record_type, _ = split("[[,\]]", query)

        try:  # try to find the record in the cache.
            record = cache.get_record(domain_name, record_type)
            print "Server sent: ", record.to_json()

        except NameError:  # case didn't find:
            s.sendto(query, (local_server_ip, port))
            data, _ = s.recvfrom(2048)
            if data.startswith("Not found"):  # case the record not found.
                print "Server sent: domain not found"

            elif data.startswith("$"):  # record found.
                json_record = data[2:]
                record = Record.from_json(json_record)
                cache.add_dynamic_record(record)  # add record to cache.
                print "Server sent: ", json_record

    s.close()
    cache.stop = True