Converts inet_pton output to bits string

@param   string  $inet  The in_addr representation of an IPv4 or IPv6 address

@return  string

@since   1.6.0
166188
protected static function inetToBits($inet)
	{
		if (\strlen($inet) == 4)
		{
			$unpacked = unpack('A4', $inet);
		}
		else
		{
			$unpacked = unpack('A16', $inet);
		}

		$unpacked = str_split($unpacked[1]);
		$binaryip = '';

		foreach ($unpacked as $char)
		{
			$binaryip .= str_pad(decbin(\ord($char)), 8, '0', STR_PAD_LEFT);
		}

		return $binaryip;
	}
1124878
private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits,
            final int toBits, final boolean pad) throws AddressFormatException {
        int acc = 0;
        int bits = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream(64);
        final int maxv = (1 << toBits) - 1;
        final int max_acc = (1 << (fromBits + toBits - 1)) - 1;
        for (int i = 0; i < inLen; i++) {
            int value = in[i + inStart] & 0xff;
            if ((value >>> fromBits) != 0) {
                throw new AddressFormatException(
                        String.format("Input value '%X' exceeds '%d' bit size", value, fromBits));
            }
            acc = ((acc << fromBits) | value) & max_acc;
            bits += fromBits;
            while (bits >= toBits) {
                bits -= toBits;
                out.write((acc >>> bits) & maxv);
            }
        }
        if (pad) {
            if (bits > 0)
                out.write((acc << (toBits - bits)) & maxv);
        } else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) {
            throw new AddressFormatException("Could not convert bits, invalid padding");
        }
        return out.toByteArray();
    }
886071
private function doSetBinaryBitsetLeInt($bitset): void
    {
        $len = \strlen($bitset);
        $int = 0;
        for ($i = 0; $i < $len; ++$i) {
            $ord = \ord($bitset[$i]);

            if ($ord && $i > \PHP_INT_SIZE - 1) {
                throw new InvalidArgumentException('out-of-range bits detected');
            }

            $int |= $ord << (8 * $i);
        }

        if ($int & (~0 << $this->enumerationCount)) {
            throw new InvalidArgumentException('out-of-range bits detected');
        }

        $this->bitset = $int;
    }
940374
public function toString($long = false)
    {
        switch (true) {
            case $this->fromAddress instanceof \IPLib\Address\IPv4:
                $chunks = explode('.', $this->fromAddress->toString());
                $chunks = array_slice($chunks, 0, -$this->asterisksCount);
                $chunks = array_pad($chunks, 4, '*');
                $result = implode('.', $chunks);
                break;
            case $this->fromAddress instanceof \IPLib\Address\IPv6:
                if ($long) {
                    $chunks = explode(':', $this->fromAddress->toString(true));
                    $chunks = array_slice($chunks, 0, -$this->asterisksCount);
                    $chunks = array_pad($chunks, 8, '*');
                    $result = implode(':', $chunks);
                } else {
                    $chunks = explode(':', $this->toAddress->toString(false));
                    $chunkCount = count($chunks);
                    $chunks = array_slice($chunks, 0, -$this->asterisksCount);
                    $chunks = array_pad($chunks, $chunkCount, '*');
                    $result = implode(':', $chunks);
                }
                break;
            default:
                throw new \Exception('@todo'); // @codeCoverageIgnore
        }

        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")
47854
public static Inet4Address forIPv4String(String ipString) {
        requireNonNull(ipString);

        try{
            InetAddress parsed = forString(ipString);

            if (parsed instanceof Inet4Address)
                return (Inet4Address) parsed;

        } catch(Exception ignored){}

        throw new IllegalArgumentException(format("Invalid IPv4 representation: %s", ipString));
    }
914488
public static function expandIncompleteIpv6(string $ip): string
    {
        $hextets = array_map(function ($hextet) {
            return str_pad($hextet, 4, '0', STR_PAD_LEFT);
        }, explode(':', $ip));

        return implode(':', $hextets);
    }
324564
def str_to_inet(address):
    
    # First try ipv4 and then ipv6
    try:
        return socket.inet_pton(socket.AF_INET, address)
    except socket.error:
        return socket.inet_pton(socket.AF_INET6, address)
759106
public static function IPv4toInteger($ip)
    {
        $ips = explode('.', $ip);
        $integer = 0;
        for ($i = 0; $i < 4; $i++)
        {
            $ips[$i] = intval($ips[$i] % 256);
            $ips[$i] = pow(256, 3 - $i) * intval($ips[$i]);
            $integer += $ips[$i];
        }
        return $integer;
    }
1255461
function pton6(addr, dest, index = 0) {
  if (typeof addr !== 'string') {
    throw new TypeError('Argument 1 should be a string.')
  }

  if (addr.length <= 0) {
    einval()
  }

  const isbuffer = Buffer.isBuffer(dest)
  const endp = index + IPV6_OCTETS

  if (isbuffer) {
    if (endp > dest.length) {
      throw new Error('Too small target buffer.')
    }
  }

  const buf = isbuffer ? dest : Buffer.allocUnsafe(IPV6_OCTETS)

  let i = 0
  let colonp = null
  let seenDigits = 0
  let val = 0
  let curtok = 0
  let ch = 0

  if (addr[i] === ':') {
    if (addr.length >= 2 && addr[++i] !== ':') {
      einval()
    }
  }

  curtok = i

  while ((ch = i++) < addr.length) {
    const char = code(addr[ch])

    if (isDigit(char) || isLetter16(char)) {
      val <<= 4

      if (isDigit(char)) {
        val |= char - CHAR0
      } else if (isLetter16Low(char)) {
        val |= char - CHARa + 10
      } else if (isLetter16Up(char)) {
        val |= char - CHARA + 10
      }

      if (++seenDigits > 4) {
        einval()
      }
    } else if (char === CHARCOLON) {
      curtok = i

      // If it's second colon in pair.
      if (seenDigits === 0) {
        // Only one colon pair allowed.
        if (colonp !== null) {
          einval()
        }

        colonp = index
        continue
      } else if (i >= addr.length) {
        einval()
      }

      if (index + 2 > endp) {
        einval()
      }

      buf[index++] = (val >> 8) & 0xFF
      buf[index++] = val & 0xFF

      seenDigits = 0
      val = 0
    } else if (char === CHARPOINT) {
      pton4(addr.slice(curtok), buf, index)
      index += IPV4_OCTETS
      seenDigits = 0
      break
    } else {
      einval()
    }
  }

  // Handle last pair.
  if (seenDigits > 0) {
    if (index + 2 > endp) {
      einval()
    }

    buf[index++] = (val >> 8) & 0xFF
    buf[index++] = val & 0xFF
  }

  if (colonp !== null) {
    const n = index - colonp

    if (index === endp) {
      einval()
    }

    buf.copyWithin(endp - n, colonp, colonp + n)
    fill(buf, 0, colonp, endp - n)
  }

  return buf
}
436241
def in6_isincluded(addr, prefix, plen):
    
    temp = inet_pton(socket.AF_INET6, addr)
    pref = in6_cidr2mask(plen)
    zero = inet_pton(socket.AF_INET6, prefix)
    return zero == in6_and(temp, pref)
1038832
protected function packBitString($bits, $len)
    {
        $bits = substr($bits, 0, $len);
        // Pad input with zeros to next multiple of 4 above $len
        $bits = str_pad($bits, 4 * (int) (($len + 3) / 4), '0');

        // Split input into chunks of 4 bits, convert each to hex and pack them
        $nibbles = str_split($bits, 4);
        foreach ($nibbles as $i => $nibble) {
            $nibbles[$i] = base_convert($nibble, 2, 16);
        }

        return pack('H*', implode('', $nibbles));
    }
1195099
def inet_pton(af, addr):
    """"""
    # Will replace Net/Net6 objects
    addr = plain_str(addr)
    # Use inet_pton if available
    try:
        return socket.inet_pton(af, addr)
    except AttributeError:
        try:
            return _INET_PTON[af](addr)
        except KeyError:
            raise socket.error("Address family not supported by protocol")
271630
public static function reverseIpv4(string $ip): string
    {
        $octets = array_reverse(explode('.', $ip));

        return implode('.', $octets).'.in-addr.arpa.';
    }
386883
public function generateOneTime($initKey = null, $timestamp = null)
    {
        $initKey = ($initKey == null) ? $this->getInitKey() : $initKey;
        $timestamp = ($timestamp == null) ? $this->generateTimestamp() : $timestamp;

        $hash = hash_hmac (
            'sha1',
            pack('N*', 0) . pack('N*', $timestamp),
            $initKey,
            true
        );

        return str_pad($this->truncateHash($hash), $this->getCodeLength(), '0', STR_PAD_LEFT);
    }
612273
static InetAddress inet4FromInt(int address) {
        byte[] addr = new byte[4];
        addr[0] = (byte) ((address >>> 24) & 0xFF);
        addr[1] = (byte) ((address >>> 16) & 0xFF);
        addr[2] = (byte) ((address >>> 8) & 0xFF);
        addr[3] = (byte) (address & 0xFF);
        try {
            return InetAddress.getByAddress(addr);
        } catch (UnknownHostException uhe) {
            throw new AssertionError("Should not reach here");
        }
    }
866155
def _ipv4_text_to_int(self, ip_text):
        """"""
        if ip_text is None:
            return None
        assert isinstance(ip_text, str)
        return struct.unpack('!I', addrconv.ipv4.text_to_bin(ip_text))[0]