示例#1
0
 def __fill_values(self,value_list):            
     for val in value_list:
         #TODO: Before remove brackets and parenthesis
         #we should agroup this info
         val = TextUtils(val).remove_chars(self.__r_chars)
         
         #Test if it is a domain
         if self.__is_domain(val):
             self._values['domain'] = val
         #Test if it is a ipv4
         elif WhatIs(val).IsIPv4():
             self._values['ip'] = ip(val)
         #Test if it is a ipv6
         #TODO:Check
         #BUG:Check if it really degtect IPv6
         elif WhatIs(val).IsIPv6():
             self._values['ip'] = ip(val)
         #Otherwise
         else:
             #It could be a tuple ip:port
             if val.find(':') != -1:
                 possible_ip,*port = val.split(':')
                 if WhatIs(possible_ip).IsIP():
                     self._values['ip'] = ip(possible_ip)
                     self._values['port'] = port
             #Or somenthing else
             else:
                 self._values['extra'].append(val)
示例#2
0
文件: ospfclient.py 项目: mjstapp/frr
    async def _ready_msg(self, mt, msg, extra, lsa_type, otype, addr):
        if lsa_type == LSA_TYPE_OPAQUE_LINK:
            e = "ifaddr {}".format(ip(addr))
        elif lsa_type == LSA_TYPE_OPAQUE_AREA:
            e = "area {}".format(ip(addr))
        else:
            e = ""
        logging.info(
            "RECV: %s ready notify for %s opaque-type %s%s",
            self,
            lsa_typename(lsa_type),
            otype,
            e,
        )

        # Signal all waiting senders they can send now.
        async with self.ready_lock:
            cond = self.ready_cond[lsa_type].get(otype)
            self.ready_cond[lsa_type][otype] = True

        if cond is True:
            logging.warning(
                "RECV: dup ready received for %s opaque-type %s",
                lsa_typename(lsa_type),
                otype,
            )
        elif cond:
            for evt in cond:
                evt.set()
示例#3
0
文件: ospfclient.py 项目: mjstapp/frr
async def async_main(args):
    c = OspfOpaqueClient(args.server)
    await c.connect()

    try:
        # Start handling async messages from server.
        if sys.version_info[1] > 6:
            asyncio.create_task(c._handle_msg_loop())
        else:
            asyncio.get_event_loop().create_task(c._handle_msg_loop())

        await c.req_lsdb_sync()
        await c.req_reachable_routers()
        await c.req_ism_states()
        await c.req_nsm_states()

        if args.actions:
            for action in args.actions:
                _s = action.split(",")
                what = _s.pop(False)
                ltype = int(_s.pop(False))
                if ltype == 11:
                    addr = ip(0)
                else:
                    aval = _s.pop(False)
                    try:
                        addr = ip(int(aval))
                    except ValueError:
                        addr = ip(aval)
                oargs = [addr, ltype, int(_s.pop(False)), int(_s.pop(False))]
                assert len(_s) <= 1, "Bad format for action argument"
                try:
                    b = bytes.fromhex(_s.pop(False))
                except IndexError:
                    b = b""
                logging.info("opaque data is %s octets", len(b))
                # Needs to be multiple of 4 in length
                mod = len(b) % 4
                if mod:
                    b += b"\x00" * (4 - mod)
                    logging.info("opaque padding to %s octets", len(b))

                if what.casefold() == "add":
                    await c.add_opaque_data(*oargs, b)
                else:
                    assert what.casefold().startswith("del")
                    await c.delete_opaque_data(*oargs)
            if args.exit:
                return 0
    except Exception as error:
        logging.error("async_main: unexpected error: %s", error, exc_info=True)
        return 2

    try:
        logging.info("Sleeping forever")
        while True:
            await asyncio.sleep(120)
    except EOFError:
        logging.info("Got EOF from OSPF API server on async notify socket")
        return 2
    def __fill_values(self, value_list):
        for val in value_list:
            #TODO: Before remove brackets and parenthesis
            #we should agroup this info
            val = TextUtils(val).remove_chars(self.__r_chars)

            #Test if it is a domain
            if self.__is_domain(val):
                self._values['domain'] = val
            #Test if it is a ipv4
            elif WhatIs(val).IsIPv4():
                self._values['ip'] = ip(val)
            #Test if it is a ipv6
            #TODO:Check
            #BUG:Check if it really degtect IPv6
            elif WhatIs(val).IsIPv6():
                self._values['ip'] = ip(val)
            #Otherwise
            else:
                #It could be a tuple ip:port
                if val.find(':') != -1:
                    possible_ip, *port = val.split(':')
                    if WhatIs(possible_ip).IsIP():
                        self._values['ip'] = ip(possible_ip)
                        self._values['port'] = port
                #Or somenthing else
                else:
                    self._values['extra'].append(val)
示例#5
0
文件: ospfclient.py 项目: mjstapp/frr
 async def _if_msg(self, mt, msg, extra, *args):
     if mt == MSG_NEW_IF:
         ifaddr, aid = args
     else:
         assert mt == MSG_DEL_IF
         ifaddr, aid = args[0], 0
     logging.info("RECV: %s ifaddr %s areaid %s", api_msgname(mt),
                  ip(ifaddr), ip(aid))
示例#6
0
 def test_ip6_to_country(self):
     # Instituto Costarricense de Electricidad y Telecom
     self.assertEqual(("CR", "Costa Rica"), self._ip_service.get_country(
         ip("2001:1330::")))
     # Wikimedia Foundation
     self.assertEqual(("US", "United States"), self._ip_service.get_country(
         ip("2620:62:c000::")))
     self.assertEqual(("ZZ", "Unknown"),
                      self._ip_service.get_country(ip("::1")))
示例#7
0
 def test_ip4_to_country(self):
     # nycourts.gov
     self.assertEqual(("US", "United States"),
                      self._ip_service.get_country(ip("207.29.128.60")))
     # Technical Research Centre of Finland
     self.assertEqual(("FI", "Finland"),
                      self._ip_service.get_country(ip("130.188.0.0")))
     self.assertEqual(("ZZ", "Unknown"),
                      self._ip_service.get_country(ip("127.0.0.1")))
示例#8
0
 def test_resolve_ip6(self):
     self.assertEqual("dns.google", self._ip_service.resolve_ip(
         GOOGLE_DNS_IP6_8888))
     self.assertEqual("dns.google", self._ip_service.resolve_ip(
         GOOGLE_DNS_IP6_8844))
     self.assertEqual(
         "localhost", self._ip_service.resolve_ip(ip("::1")))
示例#9
0
 def test_resolve_ip4(self):
     self.assertEqual(
         "dns.google", self._ip_service.resolve_ip(GOOGLE_DNS_IP4_8888))
     self.assertEqual(
         "dns.google", self._ip_service.resolve_ip(GOOGLE_DNS_IP4_8888))
     self.assertEqual(
         "localhost", self._ip_service.resolve_ip(ip("127.0.0.1")))
示例#10
0
def random_topology(n: int, e: int, c: int, bw_min=1, bw_max=10):
    nodes = []
    edges = []
    clients = []
    if n < 1:
        cprint("number of nodes should be bigger than 1", 'red')
    elif e < n - 1:
        cprint("number of edges should be bigger than #nodes - 1", 'red')
    elif e > n * (n - 1) / 2:
        cprint("number of edges should be smaller", 'red')
    else:
        nodes = [0]
        candidate_edges = [(i, j) for i in range(n) for j in range(i + 1, n)]
        for i in range(1, n):
            edge = (i, choice(nodes))
            nodes.append(i)
            edges.append(edge + (randint(bw_min, bw_max), ))
            try:
                candidate_edges.remove(edge)
            except ValueError:
                candidate_edges.remove((edge[1], edge[0]))
        for _ in range(e - n + 1):
            edge = choice(candidate_edges)
            candidate_edges.remove(edge)
            edges.append(edge + (randint(bw_min, bw_max), ))
        for i in range(c):
            clients.append(
                (str(ip(0) + i), choice(nodes), randint(bw_min, bw_max)))
    return nodes, edges, clients
示例#11
0
文件: ospfclient.py 项目: mjstapp/frr
    async def _if_change_msg(self, mt, msg, extra, ifaddr, aid, state):
        ifaddr = ip(ifaddr)
        aid = ip(aid)

        logging.info(
            "RECV: %s ifaddr %s areaid %s state %s",
            api_msgname(mt),
            ifaddr,
            aid,
            ism_name(state),
        )

        self.if_area[ifaddr] = aid
        self.ism_states[ifaddr] = state

        if self.ism_change_cb:
            self.ism_change_cb(ifaddr, aid, state)
示例#12
0
    async def _nbr_change_msg(self, mt, msg, extra, ifaddr, nbraddr, router_id, state):
        ifaddr = ip(ifaddr)
        nbraddr = ip(nbraddr)
        router_id = ip(router_id)

        logging.info(
            "RECV: %s ifaddr %s nbraddr %s router_id %s state %s",
            api_msgname(mt),
            ifaddr,
            nbraddr,
            router_id,
            nsm_name(state),
        )

        if ifaddr not in self.nsm_states:
            self.nsm_states[ifaddr] = {}
        self.nsm_states[ifaddr][(nbraddr, router_id)] = state

        if self.nsm_change_cb:
            self.nsm_change_cb(ifaddr, nbraddr, router_id, state)
示例#13
0
文件: ospfclient.py 项目: mjstapp/frr
    async def _lsa_change_msg(self, mt, msg, extra, ifaddr, aid, is_self,
                              *ls_header):
        (
            lsa_age,  # ls_age,
            _,  # ls_options,
            lsa_type,
            ls_id,
            _,  # ls_adv_router,
            ls_seq,
            _,  # ls_cksum,
            ls_len,
        ) = ls_header

        otype = (ls_id >> 24) & 0xFF

        if mt == MSG_LSA_UPDATE_NOTIFY:
            ts = "update"
        else:
            assert mt == MSG_LSA_DELETE_NOTIFY
            ts = "delete"

        logging.info(
            "RECV: LSA %s msg for LSA %s in area %s seq 0x%x len %s age %s",
            ts,
            ip(ls_id),
            ip(aid),
            ls_seq,
            ls_len,
            lsa_age,
        )
        idx = (lsa_type, otype)

        pre_lsa_size = msg_size[mt] - FMT_LSA_HEADER_SIZE
        lsa = msg[pre_lsa_size:]

        if idx in self.opaque_change_cb:
            self.opaque_change_cb[idx](mt, ifaddr, aid, ls_header, extra, lsa)

        if self.lsa_change_cb:
            self.lsa_change_cb(mt, ifaddr, aid, ls_header, extra, lsa)
示例#14
0
    async def _reachable_msg(self, mt, msg, extra, nadd, nremove):
        router_ids = struct.unpack(">{}I".format(nadd + nremove), extra)
        router_ids = [ip(x) for x in router_ids]
        logging.info(
            "RECV: %s added %s removed %s",
            api_msgname(mt),
            router_ids[:nadd],
            router_ids[nadd:],
        )
        self.reachable_routers |= set(router_ids[:nadd])
        self.reachable_routers -= set(router_ids[nadd:])
        logging.info("RECV: %s new set %s", api_msgname(mt), self.reachable_routers)

        if self.reachable_change_cb:
            logging.info("RECV: %s calling callback", api_msgname(mt))
            await self.reachable_change_cb(router_ids[:nadd], router_ids[nadd:])
示例#15
0
    async def _router_id_msg(self, mt, msg, extra, router_id):
        router_id = ip(router_id)
        logging.info("RECV: %s router ID %s", api_msgname(mt), router_id)
        old_router_id = self.router_id
        if old_router_id == router_id:
            return

        self.router_id = router_id
        logging.info(
            "RECV: %s new router ID %s older router ID %s",
            api_msgname(mt),
            router_id,
            old_router_id,
        )

        if self.router_id_change_cb:
            logging.info("RECV: %s calling callback", api_msgname(mt))
            await self.router_id_change_cb(router_id, old_router_id)
示例#16
0
    def __init__(self, server="localhost"):
        handlers = {
            MSG_READY_NOTIFY: self._ready_msg,
            MSG_LSA_UPDATE_NOTIFY: self._lsa_change_msg,
            MSG_LSA_DELETE_NOTIFY: self._lsa_change_msg,
            MSG_NEW_IF: self._if_msg,
            MSG_DEL_IF: self._if_msg,
            MSG_ISM_CHANGE: self._if_change_msg,
            MSG_NSM_CHANGE: self._nbr_change_msg,
            MSG_REACHABLE_CHANGE: self._reachable_msg,
            MSG_ROUTER_ID_CHANGE: self._router_id_msg,
        }
        super().__init__(server, handlers)

        self.ready_lock = Lock()
        self.ready_cond = {
            LSA_TYPE_OPAQUE_LINK: {},
            LSA_TYPE_OPAQUE_AREA: {},
            LSA_TYPE_OPAQUE_AS: {},
        }
        self.router_id = ip(0)
        self.router_id_change_cb = None

        self.lsid_seq_num = {}

        self.lsa_change_cb = None
        self.opaque_change_cb = {}

        self.reachable_routers = set()
        self.reachable_change_cb = None

        self.if_area = {}
        self.ism_states = {}
        self.ism_change_cb = None

        self.nsm_states = {}
        self.nsm_change_cb = None
示例#17
0
 def test_ip6_to_as(self):
     self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
         GOOGLE_DNS_IP6_8888).id)
     self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
         GOOGLE_DNS_IP6_8844).id)
     self.assertEqual(-1, self._ip_service.get_as(ip("::1")).id)
示例#18
0
    def doAction(self):
        if self.timer.isActive():
            self.startButton.setText('Start')
            self.newPBARvalue = 0
        else:
            self.startButton.setText('Pause')
            try:
                f_hn = ip(self.firstIPedit.text())
                l_hn = ip(self.lastIPedit.text())

                if f_hn > l_hn:
                    f_hn, l_hn = l_hn, f_hn
                if self.count >= 1 and f_hn != self.tmp1:
                    self.count = 0
                if self.count >= 1 and l_hn != self.tmp2:
                    self.temp_l_hn = l_hn
                self.valueIP = int(l_hn) - int(f_hn)
                self.tmp1 = f_hn
                self.tmp2 = l_hn
            except ValueError:
                # Message if user entered incorrect address. Will break function.
                QMessageBox.warning(self, 'Warning!',
                                    'IP address is incorrect. Enter again.',
                                    QMessageBox.Cancel | QMessageBox.NoButton,
                                    QMessageBox.Cancel)
                self.startButton.setText('Start')
                return

            if self.count >= 1:
                f_hn = self.temp_f_hn
                l_hn = self.temp_l_hn
                self.valuePBAR = (100 - self.step) / (self.valueIP -
                                                      self.count2)
                self.step -= self.valuePBAR

            if self.count == 0:
                self.valuePBAR = 100 / (self.valueIP + 1)
                self.resultEdit.setPlainText('')
                self.count2 = 0
                f_hn -= 1

            self.timer.start(100, self)  # Start progress bar
            self.count += 1
            QApplication.processEvents()  # Will update QTextEdit in loop

            while f_hn != l_hn:
                if self.startButton.text() == 'Start':
                    # Remember old values if you pause the application
                    self.temp_f_hn = f_hn
                    self.temp_l_hn = l_hn
                    self.timer.stop()
                    break
                self.count2 += 1
                f_hn += 1
                self.resultEdit.append('\nping {}'.format(f_hn))
                if sys.platform == 'win32':
                    result = system('ping -n 2 -w 200 {}'.format(f_hn))
                else:
                    result = system('ping -c 2 -W 2 {}'.format(f_hn))
                QApplication.processEvents()

                if result == 0:
                    self.resultEdit.append('{} - in use'.format(f_hn))
                else:
                    self.resultEdit.append('{} - is free'.format(f_hn))
            else:
                self.count = 0
                self.count2 = 0
示例#19
0
def isIPv4Address(inputString):
    try:
        ip(inputString)
    except:
        return False
    return True
示例#20
0
def get_rbndr(ip1, ip2):
    return '%.08X.%.08X.rbndr.us' % (int(ip(
        ip1.decode())), int(ip(ip2.decode())))
示例#21
0
list2 = []
if output is not None:
    line = output.split()
    for a in line:
        w = str(a).split(':')
        list1.append(w[1])
    for b in list1:
        time1 = int(b)
        time2 = int(str(minute))
        if time1 >= time2:
            list2.append(time1 - time2)
        else:
            list2.append(time2 - time1)

    parse = (str(line[list2.index(min(list2))])).split(",")
    preip = ipaddress.ip(parse[2])
    print("Pre-Nat IP: " + preip)

    try:
        cnx = mysql.connector.connect(user='******',
                                      password='******',
                                      host='127.0.0.1',
                                      database='logs_db')
        commend1 = "select mac_string from dhcp where ip_decimal = '" + preip + "' and timestamp <= '" + datetimestr + "' order by timestamp desc;"
        cursor = cnx.cursor(buffered=True)
        cursor.execute(commend1)
        macaddress = cursor.fetchone()
    except mysql.connector.Error:
        print("Error")

    if macaddress == None:
示例#22
0
def arg_parser(args):

    test=False
    packetsize=512
    payloadsize=packetsize-28
    limit=50
    pause=2
    pts=2000
    decode=False
    message=None

    if len(sys.argv) >=4:
        vector=sys.argv[1]
        if sys.argv[1] not in '-t-r':
            print("\nMust specify either -t for transmit or -r for recieve.\n")
            sys.exit()
        LOGMSG_GRP = sys.argv[2]
        try:
            is_mcast=ip(sys.argv[2]).is_multicast
            if is_mcast==False:
                print("\n%s is not a multicast address\n"%(sys.argv[2]))
                sys.exit()
        except:
            print("\nMust specify a correct IP address in dotted decimal format (x.x.x.x)\n")
            sys.exit()

        LOGMSG_PORT = int(sys.argv[3])

        if vector == '-r':
            print("Listing on: "+str(sys.argv[2])+' port: '+str(sys.argv[3])+'\n')
            if '-d' in sys.argv:
                print("\nDecoding recieved messages\n")
                decode=True
                return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode
            else:
                return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode


        elif vector == '-t':

            if '-m' in sys.argv:
                m_idx=sys.argv.index('-m')
                try:
                    message=sys.argv[m_idx+1]
                except:
                    print("Need to specify message after -m")
                    sys.exit()
                return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode
            elif '-T' in sys.argv:
                test=True
                if '-p' in sys.argv:
                    p_idx=sys.argv.index('-p')
                    try:
                        packetsize=int(sys.argv[p_idx+1])
                        payloadsize=packetsize-28
                    except:
                        print("Need to specify packet size after -p")
                        sys.exit()
                else:
                    payloadsize=1472
                    packetsize=1500
                if '-l' in sys.argv:
                    l_idx=sys.argv.index('-l')
                    try:
                        limit=int(sys.argv[l_idx+1])
                    except:
                        print("Need to specify loop number after -l")
                        sys.exit()

                else:
                    limit=100
                if '-P' in sys.argv:
                    P_idx=sys.argv.index('-P')
                    try:
                        pause=float(sys.argv[P_idx+1])
                    except:
                        print("Need to specify time to pause between loops after -P")
                        sys.exit()
                else:
                    pause=1
                if '-s' in sys.argv:
                    s_idx=sys.argv.index('-s')
                    try:
                        pts=int(sys.argv[s_idx+1])
                    except:
                        print("Need to specify number of packets sent after -s")
                        sys.exit()
                else:
                    pts=2000

                return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode

            else:
                test=True
                print("-m or -T transmit variable not specified. Defaulting to -T: %iB packetsize, %i packets per loop, %i seconds interloop pause, sending %i packets."%(payloadsize+28,limit,pause,pts))
                return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode
    else:
        if '-h' in sys.argv:
            with open ('helpfile.txt', 'r') as hf:
                f=hf.readlines()
                for i in f:
                    i.rstrip('\n')
                    i.lstrip('\t')
                    print(i)

            sys.exit()
        else:
            print("Not enough arguments. Need to at least specify '-t'(TX) or '-r'(RX) IPv4 Multicast Address and Port.\n")
            vector=input('\nSpecify -t or -r: ')
            if vector not in '-t-r':
                vector='-t'
                print('No valid vector specified. Defaulting to -t\n')
            LOGMSG_GRP=input('\nIPv4 Multicast Address: ')
            LOGMSG_PORT=int(input('\nUDP Port: '))
            if vector == '-t':
                packetsize=int(input('\nPacket Size: '))
                pts=int(input('\nPackets to send: '))
            if vector == '-r':
                packetsize,pts=(None,None)
            limit=50
            pause=1
            test=True
            if vector == '-t':
                print("\n-m or -T transmit variable not specified. Defaulting to -T: %iB packetsize, %i packets per loop, %i seconds interloop pause, sending %i packets."%(packetsize,limit,pause,pts))
            return vector,LOGMSG_GRP,LOGMSG_PORT,test,packetsize,limit,pause,pts,message,decode
示例#23
0
 def test_ip4_to_as(self):
     self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
         GOOGLE_DNS_IP4_8888).id)
     self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
         GOOGLE_DNS_IP4_8888).id)
     self.assertEqual(-1, self._ip_service.get_as(ip("127.0.0.1")).id)
示例#24
0
def main():
    token = Token()

    logging.basicConfig()

    # Creating an object
    logger = logging.getLogger()

    # Setting the threshold of logger to DEBUG
    logger.setLevel(logging.DEBUG)

    ring_routes = []
    unique_ring = set()

    pc_number = int(input("Please enter number of computers: "))
    if pc_number == 0:
        return False

    for index in range(pc_number):
        try:
            curr_ip = input(f"Enter ip number {index + 1}: ")
            curr_ip = ip(curr_ip)
            ring_routes.append(curr_ip)
            if unique_ring.__contains__(curr_ip):
                print(f"Error, ip {curr_ip} is not unique!")
                return False
            else:
                unique_ring.add(curr_ip)
        except:
            print(f"Error, ip {index + 1} is invalid!")
            return False

    while True:
        print(ring_routes)
        print("Number of ip's:" + str(len(ring_routes)))

        message = input("Please enter message: ")
        # pool = cycle(list())
        token.sent_message = message

        user_response_source = int(input("Select source: "))
        user_response_target = int(input("Select target: "))

        if 1 > user_response_target or user_response_target > pc_number or 1 > user_response_source or\
                user_response_source > pc_number:
            print("Error, out of index!")
            return False

        if user_response_target == user_response_source:
            print("Source is the same as target!")
            return False

        token.IP_source = ring_routes[user_response_source - 1]
        token.IP_target = ring_routes[user_response_target - 1]

        user_response = input("Default direction is clockwise. Do you want to change?(y/n) ")

        if user_response == 'y':
            ring_routes.reverse()

        ring_cycle = cycle(ring_routes)
        token.is_free = False

        current_item = None
        while current_item != token.IP_source:
            current_item = next(ring_cycle)
        # print(token)
        while current_item != token.IP_target:
            token.history.append(current_item)
            print(f"PC {current_item}: " + token.__str__())
            current_item = next(ring_cycle)
        else:
            token.history.append(current_item)
            token.finish_line = True
            print(f"PC {current_item}: " + token.__str__())
            print("Messsage printed: " + token.sent_message)
            current_item = next(ring_cycle)

        while current_item != token.IP_source:
            token.history.append(current_item)
            print(f"PC {current_item}: " + token.__str__())
            current_item = next(ring_cycle)
        else:
            token.free()
            print(f"PC {current_item}: " + token.__str__())

        user_response = input("Do you want to sent another message?(y/n) ")
        if user_response != 'y':
            return False
示例#25
0
import unittest

from ipaddress import ip_address as ip

from . import ip_info as ii

# Google DNS addresses will be stably assigned to Google's AS"
GOOGLE_DNS_IP4_8888 = ip("8.8.8.8")
GOOGLE_DNS_IP4_8844 = ip("8.8.4.4")
GOOGLE_DNS_IP6_8888 = ip("2001:4860:4860::8888")
GOOGLE_DNS_IP6_8844 = ip("2001:4860:4860::8844")
GOOGLE_ASN = 15169


class TestIpInfo(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._ip_service = ii.create_default_ip_info_service()

    def test_ip4_to_as(self):
        self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
            GOOGLE_DNS_IP4_8888).id)
        self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
            GOOGLE_DNS_IP4_8888).id)
        self.assertEqual(-1, self._ip_service.get_as(ip("127.0.0.1")).id)

    def test_ip6_to_as(self):
        self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
            GOOGLE_DNS_IP6_8888).id)
        self.assertEqual(GOOGLE_ASN, self._ip_service.get_as(
            GOOGLE_DNS_IP6_8844).id)