Python ipaddress.IPv4Address() Examples

The following are 30 code examples of ipaddress.IPv4Address(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipaddress , or try the search function .
Example #1
Source File: network.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def is_ipv4(string):
        """
        Checks if a string is a valid ip-address (v4)

        :param string: String to check
        :type string: str

        :return: True if an ip, false otherwise.
        :rtype: bool
        """

        try:
            ipaddress.IPv4Address(string)
            return True
        except ipaddress.AddressValueError:
            return False 
Example #2
Source File: next_hop.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def __lt__(self, other):
        # String is not comparable with None
        if (self.interface is None) and (other.interface is not None):
            return True
        if (self.interface is not None) and (other.interface is None):
            return False
        if self.interface < other.interface:
            return True
        if self.interface > other.interface:
            return False
        # Address is not comparable with None
        if (self.address is None) and (other.address is not None):
            return True
        if (self.address is not None) and (other.address is None):
            return False
        # Address of different address families are not comparable
        if (isinstance(self.address, ipaddress.IPv4Address) and
                isinstance(other.address, ipaddress.IPv6Address)):
            return True
        if (isinstance(self.address, ipaddress.IPv6Address) and
                isinstance(other.address, ipaddress.IPv4Address)):
            return False
        return self.address < other.address 
Example #3
Source File: socketutil.py    From Pyro5 with MIT License 6 votes vote down vote up
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
    """Bind the socket to a free port and return the port number.
    This code is based on the code in the stdlib's test.test_support module."""
    if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            with contextlib.suppress(socket.error):
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    if not isinstance(host, str):
        host = str(host)
    if sock.family == socket.AF_INET:
        if host == 'localhost':
            sock.bind(('127.0.0.1', 0))
        else:
            sock.bind((host, 0))
    elif sock.family == socket.AF_INET6:
        if host == 'localhost':
            sock.bind(('::1', 0, 0, 0))
        else:
            sock.bind((host, 0, 0, 0))
    else:
        raise CommunicationError("unsupported socket family: " + str(sock.family))
    return sock.getsockname()[1] 
Example #4
Source File: crawlphish.py    From ACE with Apache License 2.0 6 votes vote down vote up
def is_blacklisted(self, value):
        if is_ipv4(value):
            for cidr in self.blacklisted_cidr:
                try:
                    if IPv4Address(value) in cidr:
                        logging.debug("{} matches blacklisted cidr {}".format(value, cidr))
                        return True
                except Exception as e:
                    logging.error("failed to compare {} to {}: {}".format(value, cidr, e))
                    report_exception()

            return False

        for dst in self.blacklisted_fqdn:
            if is_subdomain(value, dst):
                logging.debug("{} matches blacklisted fqdn {}".format(value, dst))
                return True

        return False 
Example #5
Source File: test_pyopenssl.py    From service-identity with MIT License 6 votes vote down vote up
def test_ip(self):
        """
        Returns IP patterns.
        """
        rv = extract_ids(CERT_EVERYTHING)

        assert [
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"*.wildcard.service.identity.invalid"),
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"single.service.identity.invalid"),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"1.1.1.1")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"::1")),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"2.2.2.2")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"2a00:1c38::53")),
        ] == rv 
Example #6
Source File: test_cryptography.py    From service-identity with MIT License 6 votes vote down vote up
def test_ip(self):
        """
        Returns IP patterns.
        """
        rv = extract_ids(CERT_EVERYTHING)

        assert [
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"*.wildcard.service.identity.invalid"),
            DNSPattern(pattern=b"service.identity.invalid"),
            DNSPattern(pattern=b"single.service.identity.invalid"),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"1.1.1.1")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"::1")),
            IPAddressPattern(pattern=ipaddress.IPv4Address(u"2.2.2.2")),
            IPAddressPattern(pattern=ipaddress.IPv6Address(u"2a00:1c38::53")),
        ] == rv 
Example #7
Source File: get.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def get_interface_netmask(ip_address):
    """ Get netmask of ip address' class

        Args:
            ip_address ('str'): ipv4 address

        Returns:
            ip address mask

        Raises:
            None
    """

    class_a = IPv4Address("127.0.0.0")
    class_b = IPv4Address("191.255.0.0")
    class_c = IPv4Address("223.255.255.0")
    ip_addr = IPv4Address(ip_address)
    ip_class = [("/8", class_a), ("/16", class_b), ("/24", class_c)]

    for e in ip_class:
        if ip_addr < e[1]:
            return e[0] 
Example #8
Source File: unconfigconfig.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def unconfigure_route_ref(self, conf_obj, path, **kwargs):

        paths = self._path_population([path], kwargs['device'])
        # find position that neighbor (ip) sit
        # replace ip string to IPv4Address object
        for path in paths:
            ipv4_index_list = [path.index(val) for val in path if '.' in str(val)]
            ipv6_index_list = [path.index(val) for val in path if ':' in str(val)]

            for index in ipv4_index_list:
                path[index] = IPv4Address(path[index])
            for index in ipv6_index_list:
                path[index] = IPv6Address(path[index])

        config = '\n'.join([str(conf_path) for conf_path in paths])
        log.info('With following configuration:\n{c}'
                 .format(c=config))

        Configure.conf_configure(device=kwargs['device'],
                                 conf=conf_obj,
                                 conf_structure=paths,
                                 unconfig=True) 
Example #9
Source File: unconfigconfig.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def unconfigure_route_ref(self, conf_obj, path, **kwargs):

        paths = self._path_population([path], kwargs['device'])
        # find position that neighbor (ip) sit
        # replace ip string to IPv4Address object
        for path in paths:
            ipv4_index_list = [path.index(val) for val in path if '.' in str(val)]
            ipv6_index_list = [path.index(val) for val in path if ':' in str(val)]

            for index in ipv4_index_list:
                path[index] = IPv4Address(path[index])
            for index in ipv6_index_list:
                path[index] = IPv6Address(path[index])

        config = '\n'.join([str(conf_path) for conf_path in paths])
        log.info('With following configuration:\n{c}'
                 .format(c=config))

        Configure.conf_configure(device=kwargs['device'],
                                 conf=conf_obj,
                                 conf_structure=paths,
                                 unconfig=True) 
Example #10
Source File: pseudowire.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def __new__(cls, *args, **kwargs):

        factory_cls = cls
        if cls is PseudowireIPNeighbor:
            try:
                ip = kwargs['ip']
            except KeyError:
                raise TypeError('\'ip\' argument missing')
            ip = ipaddress.ip_address(ip)
            if isinstance(ip, ipaddress.IPv4Address):
                factory_cls = PseudowireIPv4Neighbor
            elif isinstance(ip, ipaddress.IPv6Address):
                factory_cls = PseudowireIPv6Neighbor
            else:
                raise ValueError(ip)

        if factory_cls is not cls:
            self = factory_cls.__new__(factory_cls, *args, **kwargs)
        elif super().__new__ is object.__new__:
            self = super().__new__(factory_cls)
        else:
            self = super().__new__(factory_cls, *args, **kwargs)
        return self 
Example #11
Source File: general_name.py    From oss-ftp with MIT License 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #12
Source File: socks.py    From torba with MIT License 6 votes vote down vote up
def _start(self):
        self._state = self._first_response

        if isinstance(self._dst_host, ipaddress.IPv4Address):
            # SOCKS4
            dst_ip_packed = self._dst_host.packed
            host_bytes = b''
        else:
            # SOCKS4a
            dst_ip_packed = b'\0\0\0\1'
            host_bytes = self._dst_host.encode() + b'\0'

        if isinstance(self._auth, SOCKSUserAuth):
            user_id = self._auth.username.encode()
        else:
            user_id = b''

        # Send TCP/IP stream CONNECT request
        return b''.join([b'\4\1', struct.pack('>H', self._dst_port),
                         dst_ip_packed, user_id, b'\0', host_bytes]) 
Example #13
Source File: general_name.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #14
Source File: test_next_hop.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def test_next_hop_ordering():
    nhop1 = next_hop.NextHop(None, None)
    nhop2 = next_hop.NextHop("if1", None)
    nhop3 = next_hop.NextHop("if1", ipaddress.IPv4Address("1.1.1.1"))
    nhop4 = next_hop.NextHop("if1", ipaddress.IPv4Address("2.2.2.2"))
    nhop5 = next_hop.NextHop("if2", ipaddress.IPv4Address("1.1.1.1"))
    nhop6 = next_hop.NextHop("if2", ipaddress.IPv6Address("1111:1111::"))
    assert nhop1 < nhop2
    assert nhop2 < nhop3
    assert nhop3 < nhop4
    assert nhop4 < nhop5
    assert nhop5 < nhop6
    # pylint:disable=unneeded-not
    assert not nhop2 < nhop1
    assert not nhop3 < nhop2
    assert not nhop4 < nhop3
    assert not nhop5 < nhop4
    assert not nhop6 < nhop5 
Example #15
Source File: utils.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def is_ipv4(string):
        """
        Checks if a string is a valid ip-address (v4)

        :param string: String to check
        :type string: str

        :return: True if an ip, false otherwise.
        :rtype: bool
        """

        try:
            ipaddress.IPv4Address(string)
            return True
        except ipaddress.AddressValueError:
            return False 
Example #16
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
def ip_address_decrement(self,
                             ip_address: str = '192.168.1.2',
                             exit_on_failure: bool = False,
                             exit_code: int = 34,
                             quiet: bool = False) -> Union[None, str]:
        """
        Decrement IPv4 address
        :param ip_address: IPv4 address string (example: '192.168.1.2')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 33)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: IPv4 address string (example: '192.168.1.1')
        """
        try:
            return str(IPv4Address(ip_address) - 1)
        except AddressValueError:
            if quiet:
                self.print_error('Bad IPv4 address: ', str(ip_address))
            if exit_on_failure:
                exit(exit_code)
            return None 
Example #17
Source File: base.py    From raw-packet with MIT License 6 votes vote down vote up
def ip_address_increment(self,
                             ip_address: str = '192.168.1.1',
                             exit_on_failure: bool = False,
                             exit_code: int = 33,
                             quiet: bool = False) -> Union[None, str]:
        """
        Increment IPv4 address
        :param ip_address: IPv4 address string (example: '192.168.1.1')
        :param exit_on_failure: Exit in case of error (default: False)
        :param exit_code: Set exit code integer (default: 33)
        :param quiet: Quiet mode, if True no console output (default: False)
        :return: IPv4 address string (example: '192.168.1.2')
        """
        try:
            return str(IPv4Address(ip_address) + 1)
        except AddressValueError:
            if quiet:
                self.print_error('Bad IPv4 address: ', str(ip_address))
            if exit_on_failure:
                exit(exit_code)
            return None 
Example #18
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 6 votes vote down vote up
def test_find_nearby_basic(self):
        resolver = 'unused'
        ips = [
            ipaddress.IPv4Address('192.168.1.0'),
            ipaddress.IPv4Address('192.168.1.1'),
        ]
        side_effect = [
            [MockAnswer('sd1.example.com.')],
            [MockAnswer('sd2.example.com.')],
        ]

        with unittest.mock.patch.object(fierce, 'reverse_query', side_effect=side_effect):
            result = fierce.find_nearby(resolver, ips)

        expected = {
            '192.168.1.0': 'sd1.example.com.',
            '192.168.1.1': 'sd2.example.com.',
        }

        assert expected == result 
Example #19
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 6 votes vote down vote up
def test_traverse_expander_no_cross_upper_boundary(self):
        ip = ipaddress.IPv4Address('192.168.1.254')
        expand = 2

        result = fierce.traverse_expander(ip, expand)
        expected = [
            ipaddress.IPv4Address('192.168.1.252'),
            ipaddress.IPv4Address('192.168.1.253'),
            ipaddress.IPv4Address('192.168.1.254'),
            ipaddress.IPv4Address('192.168.1.255'),
        ]

        assert expected == result

    # Upper and lower bound tests are to avoid reintroducing out of
    # bounds error from IPv4Address. (no_cross_*_boundary tests won't
    # necessarily cover this; GitHub issue #29) 
Example #20
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #21
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #22
Source File: general_name.py    From teleport with Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        if not isinstance(
            value,
            (
                ipaddress.IPv4Address,
                ipaddress.IPv6Address,
                ipaddress.IPv4Network,
                ipaddress.IPv6Network
            )
        ):
            raise TypeError(
                "value must be an instance of ipaddress.IPv4Address, "
                "ipaddress.IPv6Address, ipaddress.IPv4Network, or "
                "ipaddress.IPv6Network"
            )

        self._value = value 
Example #23
Source File: socks.py    From torba with MIT License 6 votes vote down vote up
def _detect_proxy(self):
        """Return True if it appears we can connect to a SOCKS proxy,
        otherwise False.
        """
        if self.protocol is SOCKS4a:
            host, port = 'www.apple.com', 80
        else:
            host, port = ipaddress.IPv4Address('8.8.8.8'), 53

        sock = await self._connect_one(host, port)
        if isinstance(sock, socket.socket):
            sock.close()
            return True

        # SOCKSFailure indicates something failed, but that we are
        # likely talking to a proxy
        return isinstance(sock, SOCKSFailure) 
Example #24
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 5 votes vote down vote up
def test_default_expander(self):
        ip = ipaddress.IPv4Address('192.168.1.1')

        result = fierce.default_expander(ip)
        expected = [
            ipaddress.IPv4Address('192.168.1.1'),
        ]

        assert expected == result 
Example #25
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 5 votes vote down vote up
def test_wide_expander_basic(self):
        ip = ipaddress.IPv4Address('192.168.1.50')

        result = fierce.wide_expander(ip)

        expected = [
            ipaddress.IPv4Address('192.168.1.{}'.format(i))
            for i in range(256)
        ]

        assert expected == result 
Example #26
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 5 votes vote down vote up
def test_traverse_expander_basic(self):
        ip = ipaddress.IPv4Address('192.168.1.1')
        expand = 1

        result = fierce.traverse_expander(ip, expand)
        expected = [
            ipaddress.IPv4Address('192.168.1.0'),
            ipaddress.IPv4Address('192.168.1.1'),
            ipaddress.IPv4Address('192.168.1.2'),
        ]

        assert expected == result 
Example #27
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 5 votes vote down vote up
def test_traverse_expander_no_cross_lower_boundary(self):
        ip = ipaddress.IPv4Address('192.168.1.1')
        expand = 2

        result = fierce.traverse_expander(ip, expand)
        expected = [
            ipaddress.IPv4Address('192.168.1.0'),
            ipaddress.IPv4Address('192.168.1.1'),
            ipaddress.IPv4Address('192.168.1.2'),
            ipaddress.IPv4Address('192.168.1.3'),
        ]

        assert expected == result 
Example #28
Source File: server.py    From Pyro5 with MIT License 5 votes vote down vote up
def serve(objects: Dict[Any, str], host: Optional[Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address]] = "",
          port: int = 0, daemon: Optional[Daemon] = None, use_ns: bool = True, verbose: bool = True) -> None:
    """
    Basic method to fire up a daemon (or supply one yourself).
    objects is a dict containing objects to register as keys, and
    their names (or None) as values. If ns is true they will be registered
    in the naming server as well, otherwise they just stay local.
    If you need to publish on a unix domain socket, or require finer control of the daemon's
    behavior, you can't use this shortcut method. Create a Daemon yourself and use its
    appropriate methods.
    See the documentation on 'publishing objects' (in chapter: Servers) for more details.
    """
    if daemon is None:
        daemon = Daemon(host, port)
    with daemon:
        ns = core.locate_ns() if use_ns else None
        for obj, name in objects.items():
            if ns:
                localname = None  # name is used for the name server
            else:
                localname = name  # no name server, use name in daemon
            uri = daemon.register(obj, localname)
            if verbose:
                print("Object {0}:\n    uri = {1}".format(repr(obj), uri))
            if name and ns:
                ns.register(name, uri)
                if verbose:
                    print("    name = {0}".format(name))
        if verbose:
            print("Pyro daemon running.")
        daemon.requestLoop() 
Example #29
Source File: test_fierce.py    From fierce with GNU General Public License v3.0 5 votes vote down vote up
def test_traverse_expander_lower_bound_regression(self):
        ip = ipaddress.IPv4Address('0.0.0.1')
        expand = 2

        result = fierce.traverse_expander(ip, expand)
        expected = [
            ipaddress.IPv4Address('0.0.0.0'),
            ipaddress.IPv4Address('0.0.0.1'),
            ipaddress.IPv4Address('0.0.0.2'),
            ipaddress.IPv4Address('0.0.0.3')
        ]
        assert expected == result 
Example #30
Source File: artifacts.py    From ThreatIngestor with GNU General Public License v2.0 5 votes vote down vote up
def is_ipv4(self):
        """Boolean: URL network location is an IPv4 address, not a domain?"""
        parsed = urlparse(iocextract.refang_url(self.artifact))

        try:
            ipaddress.IPv4Address(parsed.netloc.split(':')[0].replace('[', '').replace(']', '').replace(',', '.'))
        except ValueError:
            return False

        return True