Strips the port from an IPv4 or IPv6 address, returns a unicode object.
5846
def strip_ip_port(ip_address):
    

    # IPv4 with or without port
    if '.' in ip_address:
        cleaned_ip = ip_address.split(':')[0]

    # IPv6 with port
    elif ']:' in ip_address:
        # Remove the port following last ':', and then strip first and last chars for [].
        cleaned_ip = ip_address.rpartition(':')[0][1:-1]

    # IPv6 without port
    else:
        cleaned_ip = ip_address

    return cleaned_ip
706670
def destroy_floating_ip(self, ip_addr):
        
        if self.api_version == 2:
            self.request('/floating_ips/' + ip_addr, method='DELETE')
        else:
            raise DoError(v2_api_required_str)
1370434
def __convertIp6PrefixStringToIp6Address(self, strIp6Prefix):
        
        prefix1 = strIp6Prefix.rstrip('L')
        prefix2 = prefix1.lstrip("0x")
        hexPrefix = str(prefix2).ljust(16,'0')
        hexIter = iter(hexPrefix)
        finalMac = ':'.join(a + b + c + d for a,b,c,d in zip(hexIter, hexIter,hexIter,hexIter))
        prefix = str(finalMac)
        strIp6Prefix = prefix[:20]
        return strIp6Prefix +':'
356458
def _get_binary_from_ipv4(self, ip_addr):
        """"""

        return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
                                                    ip_addr))[0]
461416
def parse_addr(addr, *, proto=None, host=None):
    
    port = None

    if isinstance(addr, Address):
        return addr
    elif isinstance(addr, str):
        if addr.startswith('http://'):
            proto, addr = 'http', addr[7:]
        if addr.startswith('udp://'):
            proto, addr = 'udp', addr[6:]
        elif addr.startswith('tcp://'):
            proto, addr = 'tcp', addr[6:]
        elif addr.startswith('unix://'):
            proto, addr = 'unix', addr[7:]
        a, _, b = addr.partition(':')
        host = a or host
        port = b or port
    elif isinstance(addr, (tuple, list)):
        # list is not good
        a, b = addr
        host = a or host
        port = b or port
    elif isinstance(addr, int):
        port = addr
    else:
        raise ValueError('bad value')

    if port is not None:
        port = int(port)
    return Address(proto, host, port)
328721
def addr_tuple(s):
    """"""
    if "[" in s:
        # ip v6
        if (s.count("[") != 1) or (s.count("]") != 1):
            raise ValueError("Invalid IPv6 address!")
        end = s.index("]")
        if ":" not in s[end:]:
            raise ValueError("IPv6 address does specify a port to use!")
        host, port = s[1:end], s[end+1:]
        port = int(port)
        return (host, port)
    else:
        host, port = s.split(":")
        port = int(port)
        return (host, port)
540023
def remove(self):
        
        LOGGER.debug("IPAddress.remove")
        if self.id is None:
            return None
        else:
            params = {
                'id': self.id
            }
            args = {'http_operation': 'GET', 'operation_path': 'delete', 'parameters': params}
            response = IPAddressService.requester.call(args)
            if response.rc != 0:
                LOGGER.warning(
                    'IPAddress.remove - Problem while deleting IP Address' + self.ip_address +
                    '. Reason: ' + str(response.response_content) + '-' + str(response.error_message) +
                    " (" + str(response.rc) + ")"
                )
                return self
            else:
                return None
687682
def pack_ip_addr(addr):
    """"""
    addr, port = addr
    return socket.inet_aton(addr) + struct.pack('!H', port & _short_mask)
151149
def _get_ipv6_network_from_address(address):
    
    if address['addr'].startswith('fe80') or address['addr'] == "::1":
        return None

    prefix = address['netmask'].split("/")
    if len(prefix) > 1:
        netmask = prefix[1]
    else:
        netmask = address['netmask']
    return netaddr.IPNetwork("%s/%s" % (address['addr'],
                                        netmask))
261793
def maybe_ip_addr(addr):
    

    if six.PY2 and isinstance(addr, str):
        addr = unicode(addr)  # noqa
    try:
        return ipaddress.ip_address(addr)
    except ValueError:
        pass
    return str(addr)
225953
def ipv6_to_str(ip):
    
    if isinstance(ip, numbers.Integral):
        return addrconv.ipv6.bin_to_text(type_desc.Int16.from_user(ip))
    else:
        return addrconv.ipv6.bin_to_text(ip)
370335
private static boolean mayBeIPv6Address(String input) {
        if (input == null) {
            return false;
        }

        boolean result = false;
        int colonsCounter = 0;
        int length = input.length();
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (c == '.' || c == '%') {
                // IPv4 in IPv6 or Zone ID detected, end of checking.
                break;
            }
            if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')
                    || (c >= 'A' && c <= 'F') || c == ':')) {
                return false;
            } else if (c == ':') {
                colonsCounter++;
            }
        }
        if (colonsCounter >= 2) {
            result = true;
        }
        return result;
    }
60738
def inet_ntop(af, addr):
    """"""
    if af == socket.AF_INET:
        return inet_ntoa(addr)
    elif af == socket.AF_INET6:
        # IPv6 addresses have 128bits (16 bytes)
        if len(addr) != 16:
            raise Exception("Illegal syntax for IP address")
        parts = []
        for left in [0, 2, 4, 6, 8, 10, 12, 14]:
            try: 
                value = struct.unpack("!H", addr[left:left+2])[0]
                hexstr = hex(value)[2:]
            except TypeError:
                raise Exception("Illegal syntax for IP address")
            parts.append(hexstr.lstrip("0").lower())
        result = b":".join(parts)
        while b":::" in result:
            result = result.replace(b":::", b"::")
        # Leaving out leading and trailing zeros is only allowed with ::
        if result.endswith(b":") and not result.endswith(b"::"):
            result = result + b"0"
        if result.startswith(b":") and not result.startswith(b"::"):
            result = b"0" + result
        return result
    else:
        raise Exception("Address family not supported yet")
1162266
def get_free_udp_port():
    '''
    
    '''
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    addr = sock.getsockname()
    sock.close()
    return addr[1]
684087
def RemoveForwardedIp(self, address, interface):
    
    ip = netaddr.IPNetwork(address)
    self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])
423460
def ip_v4(self, with_port: bool = False) -> str:
        
        ip = '.'.join(str(self.random.randint(0, 255)) for _ in range(4))

        if with_port:
            ip += ':{}'.format(self.port())

        return ip
322823
def remove_udp_port(self, port):
        

        if port in self._used_udp_ports:
            self._used_udp_ports.remove(port)