#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ldap.h>
#if defined(N_PLAT_NLM) && defined(LIBC)
#include <screen.h>
#endif
static char usage[] =
"\n Usage: search <host name> <port number> <login dn> <password>"
"\n <search base>\n"
"\n Example: search Acme.com 389 cn=admin,o=Acme secret ou=Sales,o=Acme\n";
int main( int argc, char **argv )
{
int version, ldapPort, i, rc, entryCount;
char *ldapHost, *loginDN, *password, *searchBase;
char *attribute, *dn, **values, *sortAttribute = "sn";
BerElement *ber;
LDAP *ld;
LDAPMessage *searchResult, *entry;
struct timeval timeOut = {10,0};
#if defined(N_PLAT_NLM) && defined(LIBC)
setscreenmode(SCR_NO_MODE);
#endif
if (argc != 6)
{
printf("%s", usage);
return (1);
}
ldapHost = argv[1];
ldapPort = atoi(argv[2]);
loginDN = argv[3];
password = argv[4];
searchBase = argv[5];
version = LDAP_VERSION3;
ldap_set_option( NULL, LDAP_OPT_PROTOCOL_VERSION, &version);
ldap_set_option( NULL, LDAP_OPT_NETWORK_TIMEOUT, &timeOut);
if (( ld = ldap_init( ldapHost, ldapPort )) == NULL)
{
printf ( "\n LDAP session initialization failed\n");
return( 1 );
}
printf ( "\n LDAP session initialized\n");
rc = ldap_simple_bind_s( ld, loginDN, password );
if (rc != LDAP_SUCCESS )
{
printf("ldap_simple_bind_s: %s\n", ldap_err2string( rc ));
ldap_unbind_s ( ld );
return( 1 );
}
printf("\n Bind successful\n");
rc = ldap_search_ext_s(
ld,
searchBase,
LDAP_SCOPE_ONELEVEL,
"(objectclass=*)",
NULL,
0,
NULL,
NULL,
&timeOut,
LDAP_NO_LIMIT,
&searchResult );
if ( rc != LDAP_SUCCESS )
{
printf("ldap_search_ext_s: %s\n", ldap_err2string( rc ));
ldap_msgfree( searchResult );
ldap_unbind_s( ld );
return ( 1 );
}
ldap_sort_entries( ld, &searchResult, sortAttribute, strcmp );
for ( entry = ldap_first_entry( ld, searchResult );
entry != NULL;
entry = ldap_next_entry( ld, entry ) )
{
if (( dn = ldap_get_dn( ld, entry )) != NULL )
{
printf("\n dn: %s\n", dn );
ldap_memfree( dn );
}
for ( attribute = ldap_first_attribute( ld, entry, &ber );
attribute != NULL;
attribute = ldap_next_attribute( ld, entry, ber ) )
{
if (( values = ldap_get_values( ld, entry, attribute)) != NULL )
{
for ( i = 0; values[i] != NULL; i++ )
printf(" %s: %s\n", attribute, values[i] );
ldap_value_free( values );
}
ldap_memfree( attribute );
}
ber_free(ber, 0);
}
entryCount = ldap_count_entries( ld, searchResult );
printf("\n Search completed successfully.\n Entries returned: %d\n",
entryCount);
ldap_msgfree( searchResult );
ldap_unbind_s( ld );
return( 0 );
}