def pack_file_lznt (buffer_data, buffer_length):
	format_and_engine = wintypes.USHORT (FORMATS["COMPRESSION_FORMAT_LZNT1"].value | ENGINES["COMPRESSION_ENGINE_MAXIMUM"].value)

	workspace_buffer_size = wintypes.ULONG()
	workspace_fragment_size = wintypes.ULONG()

	# RtlGetCompressionWorkSpaceSize
	ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize.restype = wintypes.LONG
	ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize.argtypes = (
		wintypes.USHORT,
		wintypes.PULONG,
		wintypes.PULONG
	)

	status = ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize (
		format_and_engine,
		ctypes.byref(workspace_buffer_size),
		ctypes.byref(workspace_fragment_size)
	)

	if status != 0:
		print ('RtlGetCompressionWorkSpaceSize failed: 0x{0:X} {0:d} ({1:s})'.format(status, ctypes.FormatError(status)))
		return None, 0

	# Allocate memory
	compressed_buffer = ctypes.create_string_buffer (buffer_length)
	compressed_length = wintypes.ULONG()

	workspace = ctypes.create_string_buffer (workspace_fragment_size.value)

	# RtlCompressBuffer
	ctypes.windll.ntdll.RtlCompressBuffer.restype = wintypes.LONG
	ctypes.windll.ntdll.RtlCompressBuffer.argtypes = (
		wintypes.USHORT,
		wintypes.LPVOID,
		wintypes.ULONG,
		wintypes.LPVOID,
		wintypes.ULONG,
		wintypes.ULONG,
		wintypes.PULONG,
		wintypes.LPVOID
	)

	status = ctypes.windll.ntdll.RtlCompressBuffer (
		format_and_engine,
		ctypes.addressof (buffer_data),
		ctypes.sizeof (buffer_data),
		ctypes.addressof (compressed_buffer),
		ctypes.sizeof (compressed_buffer),
		wintypes.ULONG (4096),
		ctypes.byref (compressed_length),
		ctypes.addressof (workspace)
	)

	if status != 0:
		print ('RtlCompressBuffer failed: 0x{0:X} {0:d} ({1:s})'.format (status, ctypes.FormatError(status)))
		return None, 0

	return compressed_buffer, compressed_length
예제 #2
0
파일: iphlpapi.py 프로젝트: zyhong/calibre
def _get_adapters():
    heap = GetProcessHeap()
    size = wintypes.ULONG(0)
    addresses = buf = None
    max_tries = 10
    try:
        while max_tries > 0:
            max_tries -= 1
            err = GetAdaptersAddresses(0, GAA_FLAG_INCLUDE_PREFIX, None,
                                       addresses, ctypes.byref(size))
            if err in (ERROR_SUCCESS, ERROR_NO_DATA):
                yield addresses
                break
            elif err == ERROR_BUFFER_OVERFLOW:
                if addresses is not None:
                    HeapFree(heap, 0, addresses)
                    addresses = None
                buf = _heap_alloc(heap, size)
                addresses = ctypes.cast(buf,
                                        ctypes.POINTER(IP_ADAPTER_ADDRESSES))
            else:
                raise OSError(
                    'Failed to determine size for adapters table with error: %s'
                    % err)
        if addresses is None:
            raise OSError(
                'Failed to get adapter addresses, table appears to be changing rapidly'
            )
    finally:
        if addresses is not None:
            HeapFree(heap, 0, addresses)
            addresses = None
예제 #3
0
파일: iphlpapi.py 프로젝트: zyhong/calibre
def _get_forward_table():
    heap = GetProcessHeap()
    size = wintypes.ULONG(0)
    p_forward_table = table_mem = None
    max_tries = 10

    try:
        while max_tries > 0:
            max_tries -= 1
            err = GetIpForwardTable(p_forward_table, ctypes.byref(size), 0)
            if err == ERROR_INSUFFICIENT_BUFFER:
                if p_forward_table is not None:
                    HeapFree(heap, 0, p_forward_table)
                    p_forward_table = None
                table_mem = _heap_alloc(heap, size)
                p_forward_table = ctypes.cast(
                    table_mem, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))
            elif err in (ERROR_SUCCESS, ERROR_NO_DATA):
                yield p_forward_table
                break
            else:
                raise OSError('Unable to get IP forward table. Error: %s' %
                              err)
        if p_forward_table is None:
            raise OSError(
                'Failed to get IP routing table, table appears to be changing rapidly'
            )
    finally:
        if p_forward_table is not None:
            HeapFree(heap, 0, p_forward_table)
예제 #4
0
    def _get_forward_table(self):
        heap = kernel32.GetProcessHeap()
        forward_table_size = ctypes.sizeof(Win32_MIB_IPFORWARDTABLE)
        size = wintypes.ULONG(forward_table_size)
        table_mem = self._heap_alloc(heap, size)

        p_forward_table = ctypes.cast(table_mem,
                                      ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))

        try:
            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err == self.ERROR_INSUFFICIENT_BUFFER:
                kernel32.HeapFree(heap, 0, p_forward_table)
                table_mem = self._heap_alloc(heap, size)
                p_forward_table = ctypes.cast(
                    table_mem, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))
                err = iphlpapi.GetIpForwardTable(p_forward_table,
                                                 ctypes.byref(size), 0)

            if err and err != kernel32.ERROR_NO_DATA:
                raise exception.CloudbaseInitException(
                    'Unable to get IP forward table. Error: %s' % err)

            yield p_forward_table
        finally:
            kernel32.HeapFree(heap, 0, p_forward_table)
예제 #5
0
def get_adapters(include_unconfigured=False):

    # Call GetAdaptersAddresses() with error and buffer size handling

    addressbuffersize = wintypes.ULONG(15*1024)
    retval = ERROR_BUFFER_OVERFLOW
    while retval == ERROR_BUFFER_OVERFLOW:
        addressbuffer = ctypes.create_string_buffer(addressbuffersize.value)
        retval = iphlpapi.GetAdaptersAddresses(wintypes.ULONG(AF_UNSPEC),
                                      wintypes.ULONG(0),
                                      None,
                                      ctypes.byref(addressbuffer),
                                      ctypes.byref(addressbuffersize))
    if retval != NO_ERROR:
        raise ctypes.WinError()

    # Iterate through adapters fill array
    address_infos = []
    address_info = IP_ADAPTER_ADDRESSES.from_buffer(addressbuffer)
    while True:
        address_infos.append(address_info)
        if not address_info.Next:
            break
        address_info = address_info.Next[0]


    # Iterate through unicast addresses
    result = []
    for adapter_info in address_infos:

        name = adapter_info.AdapterName
        if sys.version_info[0] > 2:
            # We don't expect non-ascii characters here, so encoding shouldn't matter
            name = name.decode()
        nice_name = adapter_info.Description
        index = adapter_info.IfIndex

        if adapter_info.FirstUnicastAddress:
            ips = enumerate_interfaces_of_adapter(adapter_info.FriendlyName, adapter_info.FirstUnicastAddress[0])
            ips = list(ips)
            result.append(shared.Adapter(name, nice_name, ips,
                                         index=index))
        elif include_unconfigured:
            result.append(shared.Adapter(name, nice_name, [],
                                         index=index))

    return result
예제 #6
0
def GetConsoleScreenBufferInfoEx(handle):
    csbie = CONSOLE_SCREEN_BUFFER_INFOEX()
    csbie.cbSize = wintypes.ULONG(ctypes.sizeof(csbie))
    _GetConsoleScreenBufferInfoEx(handle, byref(csbie))
    # work around Windows bug
    # see https://stackoverflow.com/questions/35901572/setconsolescreenbufferinfoex-bug
    csbie.srWindow.Bottom += 1
    csbie.srWindow.Right += 1
    return csbie
예제 #7
0
def lsa_lookup_authentication_package(lsa_handle, package_name):
    if not isinstance(package_name, bytes):
        package_name = package_name.encode('mbcs')
    package_name = package_name[:127]
    buf = ctypes.create_string_buffer(package_name)
    name = STRING(len(package_name), len(buf), buf)
    package = wintypes.ULONG()
    secur32.LsaLookupAuthenticationPackage(lsa_handle, ctypes.byref(name),
                                           ctypes.byref(package))
    return package.value
예제 #8
0
    def _get_ipv4_routing_table(self):
        routing_table = []

        heap = kernel32.GetProcessHeap()

        size = wintypes.ULONG(ctypes.sizeof(Win32_MIB_IPFORWARDTABLE))
        p = kernel32.HeapAlloc(heap, 0, ctypes.c_size_t(size.value))
        if not p:
            raise exception.CloudbaseInitException(
                'Unable to allocate memory for the IP forward table')
        p_forward_table = ctypes.cast(p,
                                      ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))

        try:
            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err == self.ERROR_INSUFFICIENT_BUFFER:
                kernel32.HeapFree(heap, 0, p_forward_table)
                p = kernel32.HeapAlloc(heap, 0, ctypes.c_size_t(size.value))
                if not p:
                    raise exception.CloudbaseInitException(
                        'Unable to allocate memory for the IP forward table')
                p_forward_table = ctypes.cast(
                    p, ctypes.POINTER(Win32_MIB_IPFORWARDTABLE))

            err = iphlpapi.GetIpForwardTable(p_forward_table,
                                             ctypes.byref(size), 0)
            if err != self.ERROR_NO_DATA:
                if err:
                    raise exception.CloudbaseInitException(
                        'Unable to get IP forward table. Error: %s' % err)

                forward_table = p_forward_table.contents
                table = ctypes.cast(
                    ctypes.addressof(forward_table.table),
                    ctypes.POINTER(Win32_MIB_IPFORWARDROW *
                                   forward_table.dwNumEntries)).contents

                i = 0
                while i < forward_table.dwNumEntries:
                    row = table[i]
                    routing_table.append(
                        (encoding.get_as_string(
                            Ws2_32.inet_ntoa(row.dwForwardDest)),
                         encoding.get_as_string(
                             Ws2_32.inet_ntoa(row.dwForwardMask)),
                         encoding.get_as_string(
                             Ws2_32.inet_ntoa(row.dwForwardNextHop)),
                         row.dwForwardIfIndex, row.dwForwardMetric1))
                    i += 1

            return routing_table
        finally:
            kernel32.HeapFree(heap, 0, p_forward_table)
예제 #9
0
def get_adapters():
    
    # Call GetAdaptersAddresses() with error and buffer size handling

    addressbuffersize = wintypes.ULONG(15*1024)
    retval = ERROR_BUFFER_OVERFLOW
    while retval == ERROR_BUFFER_OVERFLOW:
        addressbuffer = ctypes.create_string_buffer(addressbuffersize.value)
        retval = iphlpapi.GetAdaptersAddresses(wintypes.ULONG(AF_UNSPEC),
                                      wintypes.ULONG(0),
                                      None,
                                      ctypes.byref(addressbuffer),
                                      ctypes.byref(addressbuffersize))
    if retval != NO_ERROR:
        raise ctypes.WinError()
    
    # Iterate through adapters fill array
    address_infos = []
    address_info = IP_ADAPTER_ADDRESSES.from_buffer(addressbuffer)
    while True:
        address_infos.append(address_info)
        if not address_info.Next:
            break
        address_info = address_info.Next[0]
    
    
    # Iterate through unicast addresses
    result = []
    for adapter_info in address_infos:
        
        name = adapter_info.AdapterName
        nice_name = adapter_info.Description
        
        if adapter_info.FirstUnicastAddress:
            ips = enumerate_interfaces_of_adapter(adapter_info.FriendlyName, adapter_info.FirstUnicastAddress[0])
            ips = list(ips)
            result.append(shared.Adapter(name, nice_name, ips))

    return result
예제 #10
0
def get_handles():
    info = SYSTEM_HANDLE_INFORMATION_EX()
    length = wintypes.ULONG()
    while True:
        status = ntdll.NtQuerySystemInformation(
            SystemExtendedHandleInformation, ctypes.byref(info),
            ctypes.sizeof(info), ctypes.byref(length))
        if status != STATUS_INFO_LENGTH_MISMATCH:
            break
        ctypes.resize(info, length.value)
    if status < 0:
        raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status))
    return info.Handles
예제 #11
0
    def get_current_user(self):
        """Get the user account name from the underlying instance."""
        buf_len = wintypes.ULONG(512)
        buf = ctypes.create_unicode_buffer(512)

        ret_val = secur32.GetUserNameExW(
            self.EXTENDED_NAME_FORMAT_SAM_COMPATIBLE, buf,
            ctypes.byref(buf_len))
        if not ret_val:
            raise exception.WindowsCloudbaseInitException(
                "GetUserNameExW failed: %r")

        return buf.value.split("\\")
예제 #12
0
def get_keywords_bitmask(guid, keywords):
    """
    Queries available keywords of the provider and returns a bitmask of the associated values

    :param guid: The GUID of the ETW provider.
    :param keywords: List of keywords to resolve.
    :return Bitmask of the keyword flags ORed together
    """

    bitmask = 0
    if keywords is None or len(keywords) == 0:
        return bitmask

    # enumerate the keywords for the provider as well as the bitmask values
    provider_info = None
    providers_size = wt.ULONG(0)
    status = tdh.TdhEnumerateProviderFieldInformation(
        ct.byref(guid),
        tdh.EventKeywordInformation,
        provider_info,
        ct.byref(providers_size))

    if status == tdh.ERROR_INSUFFICIENT_BUFFER:

        provider_info = ct.cast((ct.c_char * providers_size.value)(), ct.POINTER(tdh.PROVIDER_FIELD_INFOARRAY))
        status = tdh.TdhEnumerateProviderFieldInformation(
            ct.byref(guid),
            tdh.EventKeywordInformation,
            provider_info,
            ct.byref(providers_size))

    if tdh.ERROR_SUCCESS != status and tdh.ERROR_NOT_FOUND != status:
        raise ct.WinError(status)

    if provider_info:
        field_info_array = ct.cast(provider_info.contents.FieldInfoArray, ct.POINTER(tdh.PROVIDER_FIELD_INFO))
        provider_keywords = {}
        for i in range(provider_info.contents.NumberOfElements):
            provider_keyword = rel_ptr_to_str(provider_info, field_info_array[i].NameOffset)
            provider_keywords[provider_keyword] = field_info_array[i].Value

        for keyword in keywords:
            if keyword in provider_keywords:
                bitmask |= provider_keywords[keyword]

    return bitmask
예제 #13
0
파일: winip.py 프로젝트: liuzhao1006/ICOM
def GetAdaptersAddresses_info(text=None):
    ipinfo = []
    if g_dll_handle is None:
        initialize_dll()
    hlib = g_dll_handle
    if hlib is None:
        return -1, ''
    adapterIpAddr = IP_ADAPTER_ADDRESSES()
    padapter = cast(byref(adapterIpAddr), POINTER(IP_ADAPTER_ADDRESSES))
    ulOutBufLen = wintypes.ULONG(sizeof(adapterIpAddr))
    flags = c_uint(GAA_FLAGS.GAA_FLAG_INCLUDE_PREFIX
                   | GAA_FLAGS.GAA_FLAG_INCLUDE_GATEWAYS
                   | GAA_FLAGS.GAA_FLAG_INCLUDE_ALL_INTERFACES)
    print('flags', flags, ulOutBufLen, padapter)
    ret = hlib.GetAdaptersAddresses(c_int(0), flags, c_void_p(0),
                                    byref(adapterIpAddr), byref(ulOutBufLen))
    if ERROR_BUFFER_OVERFLOW == ret:
        print('ERROR_BUFFER_OVERFLOW', flags, ulOutBufLen.value)
        adapterIpAddr = c_buffer(b'\0', ulOutBufLen.value +
                                 16)  #add aditonal 64 bytes
        padapter = cast(byref(adapterIpAddr), POINTER(IP_ADAPTER_ADDRESSES))
    elif 0 != ret:
        return (ret, ipinfo)

    ret = hlib.GetAdaptersAddresses(c_int(0), flags, c_void_p(0),
                                    byref(adapterIpAddr), byref(ulOutBufLen))

    if ret != 0:
        return ret, padapter
    #info = [padapter.IfIndex, padapter.AdapterName, FirstUnicastAddress, FirstAnycastAddress, FirstMulticastAddress, FirstDnsServerAddress
    for _k in padapter.contents:  #IP_ADAPTER_ADDRESSES._fields_:
        print(_k[0]),
        info = padapter.contents[_k[0]]
        if isinstance(info, wintypes.PCHAR):
            print('\t %s' % string_at(info))
        elif isinstance(info, wintypes.PWCHAR):
            print('\t %s' % wstring_at(info))
        elif isinstance(info, POINTER(IP_ADAPTER_UNICAST_ADDRESS)):
            print('\t %s' % info.contents)
        else:
            print('\t', info)
    #padapter = cast(padapter.contents.Next, POINTER(IP_ADAPTER_ADDRESSES))
    return ret, ipinfo
예제 #14
0
def get_adapter_addresses():
    net_adapters = []
    filter_flags = (iphlpapi.GAA_FLAG_SKIP_ANYCAST
                    | iphlpapi.GAA_FLAG_SKIP_MULTICAST)

    size = wintypes.ULONG()
    ret_val = iphlpapi.GetAdaptersAddresses(ws2_32.AF_UNSPEC, filter_flags,
                                            None, None, ctypes.byref(size))

    if ret_val == kernel32.ERROR_NO_DATA:
        return net_adapters

    if ret_val == kernel32.ERROR_BUFFER_OVERFLOW:
        proc_heap = kernel32.GetProcessHeap()
        p = kernel32.HeapAlloc(proc_heap, 0, size.value)
        if not p:
            raise exception.CloudbaseInitException("Cannot allocate memory")

        ws2_32.init_wsa()

        try:
            p_addr = ctypes.cast(p,
                                 ctypes.POINTER(iphlpapi.IP_ADAPTER_ADDRESSES))

            ret_val = iphlpapi.GetAdaptersAddresses(ws2_32.AF_UNSPEC,
                                                    filter_flags, None, p_addr,
                                                    ctypes.byref(size))

            if ret_val == kernel32.ERROR_NO_DATA:
                return net_adapters

            if ret_val:
                raise exception.CloudbaseInitException(
                    "GetAdaptersAddresses failed: %r" % ret_val)

            p_curr_addr = p_addr
            while p_curr_addr:
                curr_addr = p_curr_addr.contents

                xp_data_only = (curr_addr.Union1.Struct1.Length <=
                                iphlpapi.IP_ADAPTER_ADDRESSES_SIZE_2003)

                mac_address = _format_mac_address(
                    curr_addr.PhysicalAddress, curr_addr.PhysicalAddressLength)

                dhcp_enabled = (curr_addr.Flags
                                & iphlpapi.IP_ADAPTER_DHCP_ENABLED) != 0
                dhcp_server = None

                if dhcp_enabled:
                    if not xp_data_only:
                        if curr_addr.Flags & iphlpapi.IP_ADAPTER_IPV4_ENABLED:
                            dhcp_addr = curr_addr.Dhcpv4Server

                        if ((curr_addr.Flags
                             & iphlpapi.IP_ADAPTER_IPV6_ENABLED) and
                            (not dhcp_addr or not dhcp_addr.iSockaddrLength)):
                            dhcp_addr = curr_addr.Dhcpv6Server

                        if dhcp_addr and dhcp_addr.iSockaddrLength:
                            dhcp_server = _socket_addr_to_str(dhcp_addr)
                    else:
                        dhcp_server = _get_registry_dhcp_server(
                            curr_addr.AdapterName)

                unicast_addresses = []

                p_unicast_addr = curr_addr.FirstUnicastAddress
                while p_unicast_addr:
                    unicast_addr = p_unicast_addr.contents
                    unicast_addresses.append(
                        (_socket_addr_to_str(unicast_addr.Address),
                         unicast_addr.Address.lpSockaddr.contents.sa_family))
                    p_unicast_addr = ctypes.cast(
                        unicast_addr.Next,
                        ctypes.POINTER(iphlpapi.IP_ADAPTER_UNICAST_ADDRESS))

                net_adapters.append({
                    "interface_index":
                    curr_addr.Union1.Struct1.IfIndex,
                    "adapter_name":
                    curr_addr.AdapterName,
                    "friendly_name":
                    curr_addr.FriendlyName,
                    "description":
                    curr_addr.Description,
                    "mtu":
                    curr_addr.Mtu,
                    "mac_address":
                    mac_address,
                    "dhcp_enabled":
                    dhcp_enabled,
                    "dhcp_server":
                    dhcp_server,
                    "interface_type":
                    curr_addr.IfType,
                    "unicast_addresses":
                    unicast_addresses
                })

                p_curr_addr = ctypes.cast(
                    curr_addr.Next,
                    ctypes.POINTER(iphlpapi.IP_ADAPTER_ADDRESSES))

        finally:
            kernel32.HeapFree(proc_heap, 0, p)
            ws2_32.WSACleanup()

    return net_adapters
예제 #15
0
def lsa_logon_user(auth_info,
                   local_groups=None,
                   origin_name=py_origin_name,
                   source_context=None,
                   auth_package=None,
                   logon_type=None,
                   lsa_handle=None):
    from xpra.log import Logger
    log = Logger("win32")
    log("lsa_logon_user%s",
        (auth_info, local_groups, origin_name, source_context, auth_package,
         logon_type, lsa_handle))
    if local_groups is None:
        plocal_groups = PTOKEN_GROUPS()
    else:
        plocal_groups = ctypes.byref(local_groups)
    if source_context is None:
        source_context = py_source_context
    if not isinstance(origin_name, bytes):
        origin_name = origin_name.encode('mbcs')
    buf = ctypes.create_string_buffer(origin_name)
    origin_name = STRING(len(origin_name), len(buf), buf)
    if auth_package is None:
        if isinstance(auth_info, MSV1_0_S4U_LOGON):
            auth_package = NEGOTIATE_PACKAGE_NAME
        elif isinstance(auth_info, KERB_S4U_LOGON):
            auth_package = MICROSOFT_KERBEROS_NAME
        else:
            auth_package = MSV1_0_PACKAGE_NAME
    if logon_type is None:
        if isinstance(auth_info, S4ULogon):
            logon_type = Batch
        else:
            logon_type = Interactive
    profile_buffer = wintypes.LPVOID()
    profile_buffer_length = wintypes.ULONG()
    profile = None
    logonid = LUID()
    htoken = HANDLE()
    quotas = QUOTA_LIMITS()
    substatus = NTSTATUS()
    deregister = False
    if lsa_handle is None:
        lsa_handle = lsa_connect_untrusted()
        deregister = True
    try:
        if isinstance(auth_package, (str, bytes)):
            auth_package = lsa_lookup_authentication_package(
                lsa_handle, auth_package)
        try:
            args = (lsa_handle, ctypes.byref(origin_name), logon_type,
                    auth_package, ctypes.byref(auth_info),
                    ctypes.sizeof(auth_info), plocal_groups,
                    ctypes.byref(source_context), ctypes.byref(profile_buffer),
                    ctypes.byref(profile_buffer_length), ctypes.byref(logonid),
                    ctypes.byref(htoken), ctypes.byref(quotas),
                    ctypes.byref(substatus))
            log("LsaLogonUser%s", args)
            secur32.LsaLogonUser(*args)
        except WindowsError:  #@UndefinedVariable
            if substatus.value:
                raise ctypes.WinError(substatus.to_error())
            raise
        finally:
            if profile_buffer:
                address = profile_buffer.value
                buftype = PROFILE_BUFFER_TYPE.from_address(address).value
                if buftype == MsV1_0InteractiveLogon:
                    profile = MSV1_0_INTERACTIVE_PROFILE.from_address_copy(
                        address, profile_buffer_length.value)
                secur32.LsaFreeReturnBuffer(address)
    finally:
        if deregister:
            secur32.LsaDeregisterLogonProcess(lsa_handle)
    return LOGONINFO(htoken, logonid, profile, quotas)
예제 #16
0
파일: winip.py 프로젝트: liuzhao1006/ICOM
def get_adapters_info(text=None):
    ipinfo = []
    #print 'net'
    if g_dll_handle is None:
        initialize_dll()
    hlib = g_dll_handle
    if hlib is None:
        return -1, ''
    adapter = IP_ADAPTER_INFO()
    padapter = cast(byref(adapter), POINTER(IP_ADAPTER_INFO))
    ulOutBufLen = wintypes.ULONG(sizeof(adapter))

    ret = hlib.GetAdaptersInfo(byref(adapter), byref(ulOutBufLen))
    if ERROR_BUFFER_OVERFLOW == ret:
        adapter = c_buffer(b'\0',
                           ulOutBufLen.value + 128)  #add aditonal 64 bytes
        padapter = cast(byref(adapter), POINTER(IP_ADAPTER_INFO))
    elif 0 != ret:
        return (ret, ipinfo)

    ret = hlib.GetAdaptersInfo(byref(adapter), byref(ulOutBufLen))

    if ret == 0:
        while padapter is not None:
            ip_addr = str(padapter.contents.IpAddressList)
            gw_addr = str(padapter.contents.GatewayList)
            desc = str(padapter.contents.Description)

            #print ('desc',padapter.contents.Description,type(padapter.contents.Description),padapter.contents.Next)
            desc = desc.strip()
            if text != None:  #get the adapter of the given text description
                text = text.strip()
                if desc.endswith(text):
                    ipinfo.append(
                        (padapter.contents.Description, ip_addr, gw_addr,
                         ''.join([
                             '%02X-' % d for d in padapter.contents.
                             Address[0:padapter.contents.AddressLength - 1]
                         ]) + '%02X' % padapter.contents.Address[
                             padapter.contents.AddressLength - 1],
                         padapter.contents.DhcpEnabled,
                         str(padapter.contents.LeaseObtained),
                         str(padapter.contents.LeaseExpires),
                         str(padapter.contents)))

                    break
            else:
                ipinfo.append(
                    (padapter.contents.Description, ip_addr, gw_addr, ''.join([
                        '%02X-' % d for d in padapter.contents.
                        Address[0:padapter.contents.AddressLength - 1]
                    ]) + '%02X' % padapter.contents.Address[
                        padapter.contents.AddressLength - 1],
                     padapter.contents.DhcpEnabled,
                     str(padapter.contents.LeaseObtained),
                     str(padapter.contents.LeaseExpires),
                     str(padapter.contents)))
            if bool(padapter.contents.Next) is True:
                padapter = cast(padapter.contents.Next,
                                POINTER(IP_ADAPTER_INFO))
            else:
                padapter = None

    return (ret, ipinfo)