twisted.internet.abstract.isIPAddress

Here are the examples of the python api twisted.internet.abstract.isIPAddress taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

29 Examples 7

3 Source : base.py
with MIT License
from autofelix

    def resolve(self, name, timeout=(1, 3, 11, 45)):
        """Return a Deferred that will resolve a hostname.
        """
        if not name:
            # XXX - This is *less than* '::', and will screw up IPv6 servers
            return defer.succeed('0.0.0.0')
        if abstract.isIPAddress(name):
            return defer.succeed(name)
        return self.resolver.getHostByName(name, timeout)


    def stop(self):

3 Source : udp.py
with MIT License
from autofelix

    def _setAddressFamily(self):
        """
        Resolve address family for the socket.
        """
        if isIPv6Address(self.interface):
            self.addressFamily = socket.AF_INET6
        elif isIPAddress(self.interface):
            self.addressFamily = socket.AF_INET
        elif self.interface:
            raise error.InvalidAddressError(
                self.interface, 'not an IPv4 or IPv6 address')


    def __repr__(self):

3 Source : udp.py
with MIT License
from autofelix

    def connect(self, host, port):
        """
        'Connect' to remote server.
        """
        if self._connectedAddr:
            raise RuntimeError(
                "already connected, reconnecting is not currently supported "
                "(talk to itamar if you want this)")
        if not isIPAddress(host) and not isIPv6Address(host):
            raise error.InvalidAddressError(
                host, 'not an IPv4 or IPv6 address.')
        self._connectedAddr = (host, port)
        self.socket.connect((host, port))


    def _loseConnection(self):

3 Source : udp.py
with MIT License
from autofelix

    def connect(self, host, port):
        """
        'Connect' to remote server.
        """
        if self._connectedAddr:
            raise RuntimeError("already connected, reconnecting is not currently supported")
        if not abstract.isIPAddress(host) and not abstract.isIPv6Address(host):
            raise error.InvalidAddressError(
                host, 'not an IPv4 or IPv6 address.')
        self._connectedAddr = (host, port)
        self.socket.connect((host, port))


    def _loseConnection(self):

3 Source : hosts.py
with MIT License
from autofelix

    def _aRecords(self, name):
        """
        Return a tuple of L{dns.RRHeader} instances for all of the IPv4
        addresses in the hosts file.
        """
        return tuple([
            dns.RRHeader(name, dns.A, dns.IN, self.ttl,
                         dns.Record_A(addr, self.ttl))
            for addr
            in searchFileForAll(FilePath(self.file), name)
            if isIPAddress(addr)])


    def _aaaaRecords(self, name):

3 Source : hosts.py
with MIT License
from autofelix

    def _aaaaRecords(self, name):
        """
        Return a tuple of L{dns.RRHeader} instances for all of the IPv6
        addresses in the hosts file.
        """
        return tuple([
            dns.RRHeader(name, dns.AAAA, dns.IN, self.ttl,
                         dns.Record_AAAA(addr, self.ttl))
            for addr
            in searchFileForAll(FilePath(self.file), name)
            if not isIPAddress(addr)])


    def _respond(self, name, records):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_decimalDotted(self):
        """
        L{isIPAddress} should return C{True} for any decimal dotted
        representation of an IPv4 address.
        """
        self.assertTrue(isIPAddress('0.1.2.3'))
        self.assertTrue(isIPAddress('252.253.254.255'))


    def test_shortDecimalDotted(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_shortDecimalDotted(self):
        """
        L{isIPAddress} should return C{False} for a dotted decimal
        representation with fewer or more than four octets.
        """
        self.assertFalse(isIPAddress('0'))
        self.assertFalse(isIPAddress('0.1'))
        self.assertFalse(isIPAddress('0.1.2'))
        self.assertFalse(isIPAddress('0.1.2.3.4'))


    def test_invalidLetters(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_invalidLetters(self):
        """
        L{isIPAddress} should return C{False} for any non-decimal dotted
        representation including letters.
        """
        self.assertFalse(isIPAddress('a.2.3.4'))
        self.assertFalse(isIPAddress('1.b.3.4'))


    def test_invalidPunctuation(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_invalidPunctuation(self):
        """
        L{isIPAddress} should return C{False} for a string containing
        strange punctuation.
        """
        self.assertFalse(isIPAddress(','))
        self.assertFalse(isIPAddress('1,2'))
        self.assertFalse(isIPAddress('1,2,3'))
        self.assertFalse(isIPAddress('1.,.3,4'))


    def test_emptyString(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_emptyString(self):
        """
        L{isIPAddress} should return C{False} for the empty string.
        """
        self.assertFalse(isIPAddress(''))


    def test_invalidNegative(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_invalidNegative(self):
        """
        L{isIPAddress} should return C{False} for negative decimal values.
        """
        self.assertFalse(isIPAddress('-1'))
        self.assertFalse(isIPAddress('1.-2'))
        self.assertFalse(isIPAddress('1.2.-3'))
        self.assertFalse(isIPAddress('1.2.-3.4'))


    def test_invalidPositive(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_invalidPositive(self):
        """
        L{isIPAddress} should return C{False} for a string containing
        positive decimal values greater than 255.
        """
        self.assertFalse(isIPAddress('256.0.0.0'))
        self.assertFalse(isIPAddress('0.256.0.0'))
        self.assertFalse(isIPAddress('0.0.256.0'))
        self.assertFalse(isIPAddress('0.0.0.256'))
        self.assertFalse(isIPAddress('256.256.256.256'))


    def test_unicodeAndBytes(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_unicodeAndBytes(self):
        """
        L{isIPAddress} evaluates ASCII-encoded bytes as well as text.
        """
        self.assertFalse(isIPAddress(b'256.0.0.0'))
        self.assertFalse(isIPAddress(u'256.0.0.0'))
        self.assertTrue(isIPAddress(b'252.253.254.255'))
        self.assertTrue(isIPAddress(u'252.253.254.255'))


    def test_nonIPAddressFamily(self):

3 Source : test_abstract.py
with MIT License
from autofelix

    def test_nonASCII(self):
        """
        All IP addresses must be encodable as ASCII; non-ASCII should result in
        a L{False} result.
        """
        self.assertFalse(isIPAddress(b'\xff.notascii'))
        self.assertFalse(isIPAddress(u'\u4321.notascii'))

3 Source : base.py
with The Unlicense
from dspray95

    def resolve(self, name, timeout = (1, 3, 11, 45)):
        """Return a Deferred that will resolve a hostname.
        """
        if not name:
            # XXX - This is *less than* '::', and will screw up IPv6 servers
            return defer.succeed('0.0.0.0')
        if abstract.isIPAddress(name):
            return defer.succeed(name)
        return self.resolver.getHostByName(name, timeout)

    # Installation.

    # IReactorCore
    def stop(self):

3 Source : test_abstract.py
with MIT License
from fbla-competitive-events

    def test_invalidPositive(self):
        """
        L{isIPAddress} should return C{False} for a string containing
        positive decimal values greater than 255.
        """
        self.assertFalse(isIPAddress('256.0.0.0'))
        self.assertFalse(isIPAddress('0.256.0.0'))
        self.assertFalse(isIPAddress('0.0.256.0'))
        self.assertFalse(isIPAddress('0.0.0.256'))
        self.assertFalse(isIPAddress('256.256.256.256'))

3 Source : context_factory.py
with Apache License 2.0
from matrix-org

    def __init__(self, hostname: bytes, verify_certs: bool):
        self._verify_certs = verify_certs

        _decoded = hostname.decode("ascii")
        if isIPAddress(_decoded) or isIPv6Address(_decoded):
            self._is_ip_address = True
        else:
            self._is_ip_address = False

        self._hostnameBytes = hostname
        self._hostnameASCII = self._hostnameBytes.decode("ascii")

    def verify_context_info_cb(

0 Source : twisted.py
with GNU General Public License v3.0
from agajdosi

    def resolve(
        self, host: str, port: int, family: int = 0
    ) -> "Generator[Any, Any, List[Tuple[int, Any]]]":
        # getHostByName doesn't accept IP addresses, so if the input
        # looks like an IP address just return it immediately.
        if twisted.internet.abstract.isIPAddress(host):
            resolved = host
            resolved_family = socket.AF_INET
        elif twisted.internet.abstract.isIPv6Address(host):
            resolved = host
            resolved_family = socket.AF_INET6
        else:
            deferred = self.resolver.getHostByName(utf8(host))
            fut = Future()  # type: Future[Any]
            deferred.addBoth(fut.set_result)
            resolved = yield fut
            if isinstance(resolved, failure.Failure):
                try:
                    resolved.raiseException()
                except twisted.names.error.DomainError as e:
                    raise IOError(e)
            elif twisted.internet.abstract.isIPAddress(resolved):
                resolved_family = socket.AF_INET
            elif twisted.internet.abstract.isIPv6Address(resolved):
                resolved_family = socket.AF_INET6
            else:
                resolved_family = socket.AF_UNSPEC
        if family != socket.AF_UNSPEC and family != resolved_family:
            raise Exception(
                "Requested socket family %d but got %d" % (family, resolved_family)
            )
        result = [(typing.cast(int, resolved_family), (resolved, port))]
        return result


if hasattr(gen.convert_yielded, "register"):

0 Source : endpoints.py
with MIT License
from autofelix

    def _hostAsBytesAndText(host):
        """
        For various reasons (documented in the C{@ivar}'s in the class
        docstring) we need both a textual and a binary representation of the
        hostname given to the constructor.  For compatibility and convenience,
        we accept both textual and binary representations of the hostname, save
        the form that was passed, and convert into the other form.  This is
        mostly just because L{HostnameAddress} chose somewhat poorly to define
        its attribute as bytes; hopefully we can find a compatible way to clean
        this up in the future and just operate in terms of text internally.

        @param host: A hostname to convert.
        @type host: L{bytes} or C{str}

        @return: a 3-tuple of C{(invalid, bytes, text)} where C{invalid} is a
            boolean indicating the validity of the hostname, C{bytes} is a
            binary representation of C{host}, and C{text} is a textual
            representation of C{host}.
        """
        if isinstance(host, bytes):
            if isIPAddress(host) or isIPv6Address(host):
                return False, host, host.decode("ascii")
            else:
                try:
                    return False, host, _idnaText(host)
                except UnicodeError:
                    # Convert the host to _some_ kind of text, to handle below.
                    host = host.decode("charmap")
        else:
            host = normalize('NFC', host)
            if isIPAddress(host) or isIPv6Address(host):
                return False, host.encode("ascii"), host
            else:
                try:
                    return False, _idnaBytes(host), host
                except UnicodeError:
                    pass
        # `host` has been converted to text by this point either way; it's
        # invalid as a hostname, and so may contain unprintable characters and
        # such. escape it with backslashes so the user can get _some_ guess as
        # to what went wrong.
        asciibytes = host.encode('ascii', 'backslashreplace')
        return True, asciibytes, asciibytes.decode('ascii')


    def connect(self, protocolFactory):

0 Source : udp.py
with MIT License
from autofelix

    def write(self, datagram, addr=None):
        """
        Write a datagram.

        @param addr: should be a tuple (ip, port), can be None in connected
        mode.
        """
        if self._connectedAddr:
            assert addr in (None, self._connectedAddr)
            try:
                return self.socket.send(datagram)
            except socket.error as se:
                no = se.args[0]
                if no == errno.WSAEINTR:
                    return self.write(datagram)
                elif no == errno.WSAEMSGSIZE:
                    raise error.MessageLengthError("message too long")
                elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
                            ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
                    self.protocol.connectionRefused()
                else:
                    raise
        else:
            assert addr != None
            if (not isIPAddress(addr[0]) and not isIPv6Address(addr[0])
                    and addr[0] != "  <  broadcast>"):
                raise error.InvalidAddressError(
                    addr[0],
                    "write() only accepts IP addresses, not hostnames")
            if isIPAddress(addr[0]) and self.addressFamily == socket.AF_INET6:
                raise error.InvalidAddressError(
                    addr[0], "IPv6 port write() called with IPv4 address")
            if isIPv6Address(addr[0]) and self.addressFamily == socket.AF_INET:
                raise error.InvalidAddressError(
                    addr[0], "IPv4 port write() called with IPv6 address")
            try:
                return self.socket.sendto(datagram, addr)
            except socket.error as se:
                no = se.args[0]
                if no == errno.WSAEINTR:
                    return self.write(datagram, addr)
                elif no == errno.WSAEMSGSIZE:
                    raise error.MessageLengthError("message too long")
                elif no in (errno.WSAECONNREFUSED, errno.WSAECONNRESET,
                            ERROR_CONNECTION_REFUSED, ERROR_PORT_UNREACHABLE):
                    # in non-connected UDP ECONNREFUSED is platform dependent,
                    # I think and the info is not necessarily useful.
                    # Nevertheless maybe we should call connectionRefused? XXX
                    return
                else:
                    raise


    def writeSequence(self, seq, addr):

0 Source : tcp.py
with MIT License
from autofelix

    def __init__(self, host, port, bindAddress, connector, reactor=None):
        # BaseClient.__init__ is invoked later
        self.connector = connector
        self.addr = (host, port)

        whenDone = self.resolveAddress
        err = None
        skt = None

        if abstract.isIPAddress(host):
            self._requiresResolution = False
        elif abstract.isIPv6Address(host):
            self._requiresResolution = False
            self.addr = _resolveIPv6(host, port)
            self.addressFamily = socket.AF_INET6
            self._addressType = address.IPv6Address
        else:
            self._requiresResolution = True
        try:
            skt = self.createInternetSocket()
        except socket.error as se:
            err = error.ConnectBindError(se.args[0], se.args[1])
            whenDone = None
        if whenDone and bindAddress is not None:
            try:
                if abstract.isIPv6Address(bindAddress[0]):
                    bindinfo = _resolveIPv6(*bindAddress)
                else:
                    bindinfo = bindAddress
                skt.bind(bindinfo)
            except socket.error as se:
                err = error.ConnectBindError(se.args[0], se.args[1])
                whenDone = None
        self._finishInit(whenDone, skt, err, reactor)


    def getHost(self):

0 Source : udp.py
with MIT License
from autofelix

    def write(self, datagram, addr=None):
        """
        Write a datagram.

        @type datagram: L{bytes}
        @param datagram: The datagram to be sent.

        @type addr: L{tuple} containing L{str} as first element and L{int} as
            second element, or L{None}
        @param addr: A tuple of (I{stringified IPv4 or IPv6 address},
            I{integer port number}); can be L{None} in connected mode.
        """
        if self._connectedAddr:
            assert addr in (None, self._connectedAddr)
            try:
                return self.socket.send(datagram)
            except socket.error as se:
                no = se.args[0]
                if no == EINTR:
                    return self.write(datagram)
                elif no == EMSGSIZE:
                    raise error.MessageLengthError("message too long")
                elif no == ECONNREFUSED:
                    self.protocol.connectionRefused()
                else:
                    raise
        else:
            assert addr != None
            if (not abstract.isIPAddress(addr[0])
                    and not abstract.isIPv6Address(addr[0])
                    and addr[0] != "  <  broadcast>"):
                raise error.InvalidAddressError(
                    addr[0],
                    "write() only accepts IP addresses, not hostnames")
            if ((abstract.isIPAddress(addr[0]) or addr[0] == " < broadcast>")
                    and self.addressFamily == socket.AF_INET6):
                raise error.InvalidAddressError(
                    addr[0],
                    "IPv6 port write() called with IPv4 or broadcast address")
            if (abstract.isIPv6Address(addr[0])
                    and self.addressFamily == socket.AF_INET):
                raise error.InvalidAddressError(
                    addr[0], "IPv4 port write() called with IPv6 address")
            try:
                return self.socket.sendto(datagram, addr)
            except socket.error as se:
                no = se.args[0]
                if no == EINTR:
                    return self.write(datagram, addr)
                elif no == EMSGSIZE:
                    raise error.MessageLengthError("message too long")
                elif no == ECONNREFUSED:
                    # in non-connected UDP ECONNREFUSED is platform dependent, I
                    # think and the info is not necessarily useful. Nevertheless
                    # maybe we should call connectionRefused? XXX
                    return
                else:
                    raise


    def writeSequence(self, seq, addr):

0 Source : _sslverify.py
with MIT License
from autofelix

    def __init__(self, hostname, ctx):
        """
        Initialize L{ClientTLSOptions}.

        @param hostname: The hostname to verify as input by a human.
        @type hostname: L{unicode}

        @param ctx: an L{OpenSSL.SSL.Context} to use for new connections.
        @type ctx: L{OpenSSL.SSL.Context}.
        """
        self._ctx = ctx
        self._hostname = hostname

        if isIPAddress(hostname) or isIPv6Address(hostname):
            self._hostnameBytes = hostname.encode('ascii')
            self._hostnameIsDnsName = False
        else:
            self._hostnameBytes = _idnaBytes(hostname)
            self._hostnameIsDnsName = True

        self._hostnameASCII = self._hostnameBytes.decode("ascii")
        ctx.set_info_callback(
            _tolerateErrors(self._identityVerifyingInfoCallback)
        )


    def clientConnectionForTLS(self, tlsProtocol):

0 Source : twisted.py
with Apache License 2.0
from awslabs

    def resolve(self, host, port, family=0):
        # getHostByName doesn't accept IP addresses, so if the input
        # looks like an IP address just return it immediately.
        if twisted.internet.abstract.isIPAddress(host):
            resolved = host
            resolved_family = socket.AF_INET
        elif twisted.internet.abstract.isIPv6Address(host):
            resolved = host
            resolved_family = socket.AF_INET6
        else:
            deferred = self.resolver.getHostByName(utf8(host))
            resolved = yield gen.Task(deferred.addBoth)
            if isinstance(resolved, failure.Failure):
                try:
                    resolved.raiseException()
                except twisted.names.error.DomainError as e:
                    raise IOError(e)
            elif twisted.internet.abstract.isIPAddress(resolved):
                resolved_family = socket.AF_INET
            elif twisted.internet.abstract.isIPv6Address(resolved):
                resolved_family = socket.AF_INET6
            else:
                resolved_family = socket.AF_UNSPEC
        if family != socket.AF_UNSPEC and family != resolved_family:
            raise Exception('Requested socket family %d but got %d' %
                            (family, resolved_family))
        result = [
            (resolved_family, (resolved, port)),
        ]
        raise gen.Return(result)


if hasattr(gen.convert_yielded, 'register'):

0 Source : _sslverify.py
with The Unlicense
from dspray95

    def __init__(self, hostname, ctx):
        """
        Initialize L{ClientTLSOptions}.

        @param hostname: The hostname to verify as input by a human.
        @type hostname: L{unicode}

        @param ctx: an L{OpenSSL.SSL.Context} to use for new connections.
        @type ctx: L{OpenSSL.SSL.Context}.
        """
        self._ctx = ctx
        self._hostname = hostname

        if isIPAddress(hostname) or isIPv6Address(hostname):
            self._hostnameBytes = hostname.encode('ascii')
            self._sendSNI = False
        else:
            self._hostnameBytes = _idnaBytes(hostname)
            self._sendSNI = True

        self._hostnameASCII = self._hostnameBytes.decode("ascii")
        ctx.set_info_callback(
            _tolerateErrors(self._identityVerifyingInfoCallback)
        )


    def clientConnectionForTLS(self, tlsProtocol):

0 Source : twisted.py
with MIT License
from luckystarufo

    def resolve(self, host, port, family=0):
        # getHostByName doesn't accept IP addresses, so if the input
        # looks like an IP address just return it immediately.
        if twisted.internet.abstract.isIPAddress(host):
            resolved = host
            resolved_family = socket.AF_INET
        elif twisted.internet.abstract.isIPv6Address(host):
            resolved = host
            resolved_family = socket.AF_INET6
        else:
            deferred = self.resolver.getHostByName(utf8(host))
            fut = Future()
            deferred.addBoth(fut.set_result)
            resolved = yield fut
            if isinstance(resolved, failure.Failure):
                try:
                    resolved.raiseException()
                except twisted.names.error.DomainError as e:
                    raise IOError(e)
            elif twisted.internet.abstract.isIPAddress(resolved):
                resolved_family = socket.AF_INET
            elif twisted.internet.abstract.isIPv6Address(resolved):
                resolved_family = socket.AF_INET6
            else:
                resolved_family = socket.AF_UNSPEC
        if family != socket.AF_UNSPEC and family != resolved_family:
            raise Exception('Requested socket family %d but got %d' %
                            (family, resolved_family))
        result = [
            (resolved_family, (resolved, port)),
        ]
        raise gen.Return(result)


if hasattr(gen.convert_yielded, 'register'):

0 Source : federation_server.py
with Apache License 2.0
from matrix-org

def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
    """Check if the given server is allowed by the ACL event

    Args:
        server_name: name of server, without any port part
        acl_event: m.room.server_acl event

    Returns:
        True if this server is allowed by the ACLs
    """
    logger.debug("Checking %s against acl %s", server_name, acl_event.content)

    # first of all, check if literal IPs are blocked, and if so, whether the
    # server name is a literal IP
    allow_ip_literals = acl_event.content.get("allow_ip_literals", True)
    if not isinstance(allow_ip_literals, bool):
        logger.warning("Ignoring non-bool allow_ip_literals flag")
        allow_ip_literals = True
    if not allow_ip_literals:
        # check for ipv6 literals. These start with '['.
        if server_name[0] == "[":
            return False

        # check for ipv4 literals. We can just lift the routine from twisted.
        if isIPAddress(server_name):
            return False

    # next,  check the deny list
    deny = acl_event.content.get("deny", [])
    if not isinstance(deny, (list, tuple)):
        logger.warning("Ignoring non-list deny ACL %s", deny)
        deny = []
    for e in deny:
        if _acl_entry_matches(server_name, e):
            # logger.info("%s matched deny rule %s", server_name, e)
            return False

    # then the allow list.
    allow = acl_event.content.get("allow", [])
    if not isinstance(allow, (list, tuple)):
        logger.warning("Ignoring non-list allow ACL %s", allow)
        allow = []
    for e in allow:
        if _acl_entry_matches(server_name, e):
            # logger.info("%s matched allow rule %s", server_name, e)
            return True

    # everything else should be rejected.
    # logger.info("%s fell through", server_name)
    return False


def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:

0 Source : twisted.py
with GNU General Public License v3.0
from migaku-official

    def resolve(
        self, host: str, port: int, family: int = 0
    ) -> "Generator[Any, Any, List[Tuple[int, Any]]]":
        # getHostByName doesn't accept IP addresses, so if the input
        # looks like an IP address just return it immediately.
        if twisted.internet.abstract.isIPAddress(host):
            resolved = host
            resolved_family = socket.AF_INET
        elif twisted.internet.abstract.isIPv6Address(host):
            resolved = host
            resolved_family = socket.AF_INET6
        else:
            deferred = self.resolver.getHostByName(utf8(host))
            fut = Future()  # type: Future[Any]
            deferred.addBoth(fut.set_result)
            resolved = yield fut
            if isinstance(resolved, failure.Failure):
                try:
                    resolved.raiseException()
                except twisted.names.error.DomainError as e:
                    raise IOError(e)
            elif twisted.internet.abstract.isIPAddress(resolved):
                resolved_family = socket.AF_INET
            elif twisted.internet.abstract.isIPv6Address(resolved):
                resolved_family = socket.AF_INET6
            else:
                resolved_family = socket.AF_UNSPEC
        if family != socket.AF_UNSPEC and family != resolved_family:
            raise Exception(
                "Requested socket family %d but got %d" % (family, resolved_family)
            )
        result = [(typing.cast(int, resolved_family), (resolved, port))]
        return result


def install() -> None: