home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeJava and XSLTSearch this book

19.2. Searching an LDAP Directory with Net::LDAP

One of the most common actions you'll perform against LDAP is searching. If you're using LDAP as a repository for your mail aliases, you'll search the directory each time mail is sent to a given address. If you're using LDAP as a repository for user accounts, you'll search the directory every time a user logs into your system, or when a user performs a task on the system that requires information that resides only in LDAP.

Under LDAP, searching consists of three parts:

  1. Binding to a directory server by name (or by other credentials, such as Kerberos tokens) and port. You can provide a login and password for the authentication or bind anonymously if you have permissions to search or write a part of the directory.

  2. Passing your search request to the directory server.

  3. Unbinding from the directory server, thus closing the connection.

Let's say that you want to find a user called nvp in the directory server that's living on ldap.your.server. With Net::LDAP, do the following:

use Net::LDAP;

my $lsvr = 'ldap.your.domain';
my $ldap = Net::LDAP->new($lsvr)
    or die "error connecting to $lsvr: $@";

$ldap->bind;   # Bind anonymously, that is, no login and pass

my $results = $ldap->search (  # Perform a search for 'nvp'
    filter => "(&(uid=nvp) (o=your.domain))"
    );

if($results->code) {
    die "received LDAP error: @{[$results->error]};
}

foreach my $entry ($results->all_entries) {
    $entry->dump;
}

$ldap->unbind;   # Unbind and close connection


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.