OpenLDAP API Search

OpenLDAP API Search

本文关键字:Search API OpenLDAP      更新时间:2023-10-16

我正在尝试使用OpenLDAP API进行LDAP搜索。我已经成功连接并绑定到服务器。我已经用ldap_search_ext_s()完成了搜索,并用ldap_parse_result()解析了结果。然而,我似乎不知道如何获得搜索的实际结果。不幸的是,OpenLDAP C API最近发生了变化,互联网上的许多现有示例都不使用当前的API。

我已经尝试使用ldap_first_attribute()、ldap_next_attribute()和ldap_get_values(),如上所示http://www-archive.mozilla.org/directory/csdk-docs/search.htm(实施例6-13)。然而,ldap_get_values()现在似乎已被弃用,而ldap_get_values_len()是最接近的替代品。新函数没有返回char**,而是返回berval**。我试图通过创建一个值为barval**[I]的berval*来调整这个示例代码。这导致了一个成功的编译,但在ber_scanf()处进行了核心转储。

有人知道如何使用OpenLDAP C API获取LDAP搜索结果吗?

更新:

特别是,我询问如何从搜索消息中获取所请求的属性。

搜索请求的结果总是包含一系列SearchResultEntrySeachResultReference消息,该系列消息以SearchResultDone消息终止。调用getNextAttribute(以任何语言和任何API)都没有任何意义,因为搜索结果是消息列表。API应该以调用方可以简单地检索条目或引用列表的方式对条目或引用数组进行打包。寻找一种能做到这一点的方法。

在查看了OpenLDAP API源代码并了解了berval值的使用方法后,我最终偶然发现了如何获取它的值。

首先,您必须使用ldap_first_entry()获得第一个条目。然后,您需要使用ldap_first_attribute()获取该条目中的第一个属性。然后,将这些值放入带有ldap_get_values_len()的berval**数组中。然后可以使用berval[i]->bv_val访问返回的属性值。

您可以分别使用ldap_next_entry()ldap_next_attribute()获取下一个条目和属性。

我希望这能帮助到任何有类似问题的人。

希望以下功能可以帮助您,

int ldap_search_result(LDAP *ld, char *search_filter, char *search_base)
{
    LDAPMessage *result;
    BerElement *ber;
    char *attr;
    char **val;
    if(ldap_search_ext_s(ld, search_base, LDAP_SCOPE_CHILDREN, 
            search_filter, NULL, 0, NULL, NULL, NULL, -1, &result) != LDAP_SUCCESS) {
        return -1;
    }
    if(ldap_count_entries(ld,result) != 1) {    // assuming search_filter is unique, 
                                                // matches only one entry, and so
                                                // search routine returns only one entry
        return -1;
    }
    if((attr = ldap_first_attribute(ldp, result, &ber)) == NULL) {
        return -1;
    }
    do {
        if((val = ldap_get_values(ldp,result,attr)) == NULL) {
            return -1;
        }
        printf(" %s : %s n", attr, val[0]); // assuming all attributes are single -
                                             //valued.
        ldap_memfree(attr);
        ldap_value_free(val);
    while((attr = ldap_next_attribute(ld,result,ber)) != NULL);
    return 0;
}