连接例子:
#include
#include "ldap.h"
/* Adjust these setting for your own LDAP server */
#define HOSTNAME "localhost"
#define PORT_NUMBERLDAP_PORT
#define FIND_DN "uid=bjensen, ou=People, o=Airius.com"
int
main( int argc, char **argv )
{
LDAP*ld;
LDAPMessage*result, *e;
BerElement*ber;
char*a;
char**vals;
int i, rc;
/* Get a handle to an LDAP connection. */
if ( (ld = ldap_init( HOSTNAME, PORT_NUMBER )) == NULL ) {
perror( "ldap_init" );
return( 1 );
}
/* Bind anonymously to the LDAP server. */
rc = ldap_simple_bind_s( ld, NULL, NULL );
if ( rc != LDAP_SUCCESS ) {
fprintf(stderr, "ldap_simple_bind_s: %s\n", ldap_err2string(rc));
return( 1 );
}
/* Search for the entry. */
if ( ( rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
"(objectclass=*)", NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
LDAP_NO_LIMIT, &result ) ) != LDAP_SUCCESS ) {
fprintf(stderr, "ldap_search_ext_s: %s\n", ldap_err2string(rc));
return( 1 );
}
/* Since we are doing a base search, there should be only
one matching entry. */
e = ldap_first_entry( ld, result );
if ( e != NULL ) {
printf( "\nFound %s:\n\n", FIND_DN );
/* Iterate through each attribute in the entry. */
for ( a = ldap_first_attribute( ld, e, &ber );
a != NULL; a = ldap_next_attribute( ld, e, ber ) ) {
/* For each attribute, print the attribute name and values. */
if ((vals = ldap_get_values( ld, e, a)) != NULL ) {
for ( i = 0; vals != NULL; i++ ) {
printf( "%s: %s\n", a, vals );
}
ldap_value_free( vals );
}
ldap_memfree( a );
}
if ( ber != NULL ) {
ber_free( ber, 0 );
}
}
ldap_msgfree( result );
ldap_unbind( ld );
return( 0 );
} i. Novell函数库:
Novel提供了基于普通LDAP函数库的扩展,主要包括两个部分:针对Novel eDirectory服务器产品的扩展,其次是对如ldapsearch等常用函数的扩展。详情可从: http://developer.novell.com/ndk/qstart/opensource.htm#ldapc
获得帮助; ii. Netscape函数库;
Netscape一度是企业级目录服务提供者,许多LDAP的C例子,实际上都是基于Netscape服务器的。但在Netscape被收购后,其目录服务成了iPlanet和SUN eDirectory产品的一部分,出于支持JAVA和iplanet产品的缘故,SUN对该产品和相关库的支持远不够积极,特别是对linux的支持不够充分,估计也与保护solaris产品有关。 iii. Mozilla函数库:
Mozilla可以看作是Netscape的另一个分支。准确地说,Netscape本来就是源于Mozilla。Mozilla是也是一个开源的项目,提供完整的C-SDK,缺点是对linux的支持不够充分。 c) Perl接口 Perl 的NET::LDAP模块中包括有完整的LDAP目录访问函数,只要安装NET::LDAP就可以完成正常的LDAP目录访问;但在安装NET::LDAP模块前,必须先安装Convert::ASN1模块,该模块可以从CPAN下载。
例:
#!/usr/bin/perl
use warnings;
use strict;
use Net::LDAP;
use Net::LDAP::Util qw(ldap_error_text);
my $server = "localhost";
my $ldap = new Net::LDAP($server) ||
die("failed to connect to server.$!\n");
my $mesg = $ldap->bind("cn=Manager,dc=daifu,dc=com", password => "secret");
die ("bind failed with ",ldap_error_text($mesg->code()),"\n")
if $mesg->code();
die ("search failed with ",ldap_error_text($mesg->code()),"\n")
if $mesg->code();
print "Count is ",$mesg->count(),"\n";
while (my $entry = $mesg->shift_entry()) {
print "dn:",$entry->dn(),"\n";
for my $attr($entry->attributes()) {
for my $val($entry->get_value($attr)) {
print "$attr:$val\n";
}
}