现在的位置: 首页 > 综合 > 正文

c操作ldap

2013年10月20日 ⁄ 综合 ⁄ 共 2417字 ⁄ 字号 评论关闭

http://blog.csdn.net/lxt643755936/article/details/8196515

#include "stdafx.h"

#include <windows.h>   

#include <winldap.h> 

#include <stdio.h> 

#pragma comment(lib,"crypt32.lib")

#pragma comment(lib,"Wldap32.lib")

LDAP *ld;

LDAPMessage *res,*e;

char *dn, *a, *sdn, **vals;

BerElement *ptr;

char *host="192.168.0.237";

int port=389;

char * rdn="cn=root,dc=example,dc=com";

char * passwd="123456";

int connect()

{

 ld = ldap_open(host,port);

 if (ld==NULL)

  printf("connect failed\n");

 else

  printf("connect success\n");

  

 if(ldap_simple_bind_s(ld,"cn=root,dc=example,dc=com","123456")!=LDAP_SUCCESS) 

     ldap_perror( ld, "ldap_simple_bind_s" ); 

 else

  printf("bind success\n");

}

int search()

{

 sdn="dc=example,dc=com";

 if (ldap_search_s(ld,sdn,LDAP_SCOPE_SUBTREE,"(objectclass=*)",NULL,0,&res) 

  != LDAP_SUCCESS) 

 { 

  ldap_perror(ld,"ldap_search_s"); 

  return -1; 

 } 

 

 for(e=ldap_first_entry(ld,res);e!=NULL;e=ldap_next_entry(ld,e)) 

 { 

  dn=ldap_get_dn(ld,e); 

  printf("dn: %s \n",dn); 

  ldap_memfree( dn ); 

  for ( a = ldap_first_attribute( ld, e, &ptr );a != NULL;a = ldap_next_attribute( ld, e, ptr ) )

  { 

   //printf( "attr= %s:  ",a ); 

   vals = ldap_get_values( ld, e, a ); 

   for ( int i = 0; vals[i] != NULL; i++ )  

    printf(" %s=%s \n",a,vals[i]); 

  

   ldap_value_free( vals ); 

  }

  printf("\n"); 

   

 } 

 ldap_msgfree(res);

}

int modify()

{

 char *passwd[] = {"654321",NULL};  

 

 LDAPMod mod1 = {LDAP_MOD_REPLACE,"esmaPassword",passwd}; 

 LDAPMod *lmod[] = {&mod1,NULL}; 

 sdn = "uid=zyh,cn=Teachers,cn=Users,dc=example,dc=com"; 

 if (ldap_modify_s(ld,sdn,lmod)!=LDAP_SUCCESS) 

 { 

  ldap_perror( ld, "ldap_modify_s" ); 

  return( -1 ); 

 }

 else

 {

  printf("modify success\n");

 } 

}

int add()

{

 char *cn_values[] = {"ea",NULL}; 

 char *sn_values[] = {"ea",NULL}; 

 char *userPassword_values[] = {"123456",NULL}; 

 char *objectClass_values[] = {"person",NULL}; 

 sdn = "cn=ea,dc=example,dc=com";

 

 LDAPMod mod0 = {LDAP_MOD_ADD,"cn",cn_values}; 

 LDAPMod mod1 = {LDAP_MOD_ADD,"sn",sn_values}; 

 LDAPMod mod2 = {LDAP_MOD_ADD,"objectClass",objectClass_values}; 

 LDAPMod mod3 = {LDAP_MOD_ADD,"userPassword",userPassword_values}; 

 LDAPMod *lmod[] = {&mod0,&mod1,&mod2,&mod3,NULL};

 

 if(ldap_add_s(ld,sdn,lmod)!=LDAP_SUCCESS)

 { 

  ldap_perror(ld,"ldap_add_s error"); 

  return( -1 ); 

 } 

 else

 {

  printf("add success\n");

 }

}

int del()

{

 if( ldap_delete_s(ld,"cn=ea,dc=example,dc=com") == -1) 

 { 

  ldap_perror(ld,"ldap_delete_s"); 

  return (-1);         

 } 

 else

 {

  printf("delete success\n");

 }

}

int main(int argv,int argc[])

{

 connect();

 search();

 //modify();

 //add();

 //del();

 ldap_unbind(ld);  

 return 0;

}

抱歉!评论已关闭.