Exemple #1
0
def str_to_int(addr, flags=0):
    """
    :param addr: An IPv4 dotted decimal address in string form.

    :param flags: decides which rules are applied to the interpretation of the
        addr value. Supported constants are INET_PTON and ZEROFILL. See the
        netaddr.core docs for details.

    :return: The equivalent unsigned integer for a given IPv4 address.
    """
    if flags & ZEROFILL:
        addr = '.'.join(['%d' % int(i) for i in addr.split('.')])

    try:
        if flags & INET_PTON:
            return _struct.unpack('>I', _inet_pton(AF_INET, addr))[0]
        else:
            return _struct.unpack('>I', _inet_aton(addr))[0]
    except:
        raise AddrFormatError('%r is not a valid IPv4 address string!' % addr)
Exemple #2
0
def expand_partial_address(addr):
    """
    Expands a partial IPv4 address into a full 4-octet version.

    :param addr: an partial or abbreviated IPv4 address

    :return: an expanded IP address in presentation format (x.x.x.x)

    """
    tokens = []

    error = AddrFormatError('invalid partial IPv4 address: %r!' % addr)

    if isinstance(addr, _str_type):
        if ':' in addr:
            #   Ignore IPv6 ...
            raise error

        try:
            if '.' in addr:
                tokens = ['%d' % int(o) for o in addr.split('.')]
            else:
                tokens = ['%d' % int(addr)]
        except ValueError:
            raise error

        if 1 <= len(tokens) <= 4:
            for i in range(4 - len(tokens)):
                tokens.append('0')
        else:
            raise error

    if not tokens:
        raise error

    return '%s.%s.%s.%s' % tuple(tokens)