[Date Prev][Date Next] [Chronological] [Thread] [Top]

Re: Sample Code?




Does anyone have a simple sample c code thats init's, binds and unbinds
I can have a look at?

Something like this. It's not really a beauty of an example. I edited a few snippets, but you'll get the picture. Compile with: gcc -O2 -Wall -llber -lldap ldapexample.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <syslog.h>
#include <time.h>
#include <stdarg.h>
#include <lber.h>
#include <ldap.h>
#include <limits.h>

#define MY_LDAP_SERVER            "localhost"
#define MY_LDAP_BASE              "o=MyOrg,c=MyCountry"
#define MY_LDAP_ATTR_LOGIN        "uid"

LDAP *ld=NULL;


int my_ldap_open() /* Get a handle to an LDAP connection. */

{
  if ((ld = ldap_open(MY_LDAP_SERVER, LDAP_PORT)) == NULL)  {
    syslog(LOG_ERR,"ldap_open(%s %u) failed",MY_LDAP_SERVER,LDAP_PORT);
    return(1);
  }
  ldap_enable_cache(ld,3600,0);
  return(0);
}


int my_ldap_init(char *bindas, char *credentials)

{
  int ldapr;
  char bindas2[129];

if (!ld) if (my_ldap_open()) return(1);
if ((!credentials) || (!bindas)) return(3);
if (bindas && credentials) {
snprintf(bindas2,128,"%s=%s,%s",MY_LDAP_ATTR_LOGIN,bindas,MY_LDAP_BASE);
if ((ldapr = ldap_bind_s(ld, bindas2, credentials, LDAP_AUTH_SIMPLE)) != LDAP_SUCCESS) {
switch (ldapr) {
case LDAP_NO_SUCH_OBJECT:
return(2);
case LDAP_INVALID_CREDENTIALS:
return(3);
default:
return(4+ldapr);
}
}
}
return(0);
}



void my_ldap_final(int c)

{
  int ldapr=LDAP_SUCCESS;

  if (ld) {
    ldapr = ldap_unbind(ld);
    ld = NULL;
  }
  if (ldapr != LDAP_SUCCESS)
    syslog(LOG_ERR,"ldap_unbind_s() failed : %s",ldap_err2string(ldapr));
  if (c) exit(c);
}


int main()

{
  my_ldap_init("login","password");
  my_ldap_final(0);
  return(0);
}

/\lbert

/---------------------------------------------------------------------\
| Albert Siersema aka loonatic | There are no deadlines any deadlier  |
|                              |  nor limits more limiting than those |
|          albert@friendly.net |  we set (for) ourselves         (la) |
\---------------------------------------------------------------------/