下面代碼是從<Windows 2000 Active Directory程序設計> 書上敲下來的, 做了一些修改改, 代碼現在能通過編譯,
但是裏面有些不足之處, 如很多地方沒有判斷是否處理成功(代碼中// TODO: 處), 這樣會導致程序掛掉.
等我有時間調試好程序後再傳上來. 之後我會把書上相關的代碼儘量多敲一些下來方便大家.
/************************************************************************/
/* Windows2000ActiveDirectory程序設計.pdf P36 */
/* LDAPEnumTop.c */
/* 作用: 連接到AD域, 並查找頂層對象, 可以通過遞歸此函數列出所有對象*/
/************************************************************************/
#include <Windows.h>
#include <stdio.h>
#include <Winldap.h>
#pragma comment(lib,"wldap32.lib") // 書上沒有此項, 增加此項才能通過編譯
int main(int argc, char **argv)
{
PLDAP pldapSession; // LDAP session data
PLDAPMessage plmsgSearchResponse; // server allocated response to search request
PLDAPMessage plmsgEntry; // server allocated response to entry request
PCHAR pszDN; // LDAP distinguished name stringn
PCHAR* ppszDomainDN = NULL; // Domain DN(string allocated by LDAP library)
// start an LDAP session to nearest LDAP server
// 不用host 的方法只有Win2000上才能用, 2003 上不能使用
pldapSession = ldap_init(NULL, LDAP_PORT); // ldap_init(hostname, port)
// TODO: 判斷成功與否, 當初始化失敗時不應繼續
// authenticate using user's current credentials
ldap_bind_s(pldapSession, NULL, NULL, LDAP_AUTH_NEGOTIATE);
// serarch the root of the LDAP server
ldap_search_s(pldapSession, // session handle
NULL, // locaation to start search, NULL specifies top level
LDAP_SCOPE_BASE, // search only the root entry (rootDSE)
NULL, // search for all objects (only one for the rootDSE)
NULL, // no attributes specified, return all attributes
FALSE, // return attributes types and values
&plmsgSearchResponse); // server allocates and fills with search results
// TODO: 判斷是否成功
// using the defaultNameingContext attribute, get the distinguished name of the domain
ppszDomainDN = ldap_get_values(pldapSession, plmsgSearchResponse,
"defaultNamingContest");
// TODO: 判斷是否成功
// display info
printf("Listing objects at %s.\nPress CTRL+C to interrupt.\n", *ppszDomainDN);
// search first level of root container
ldap_search_s(pldapSession, // session handle
*ppszDomainDN, // location in directory to start search
LDAP_SCOPE_ONELEVEL, // search first level below the base entry
NULL, // SEARCH FOR ALL objects
NULL, // no attributes spectified, return all attributes
FALSE, // return attributes types and values
&plmsgSearchResponse); // server allocates and fills with search results
// TODO: 判斷是否成功
// get the first entry form the search results
plmsgEntry = ldap_first_entry(pldapSession, plmsgSearchResponse);
while(plmsgEntry){
// get the distinguished name of the entry
pszDN = ldap_get_dn(pldapSession, plmsgEntry);
// TODO: 判斷是否成功
// print the DN of the entry
printf("%s\n", pszDN);
// get next entry
plmsgEntry = ldap_next_entry(pldapSession, plmsgEntry);
}
// instruct the library toi free the search results
ldap_value_free(ppszDomainDN);
// close the session
ldap_unbind(pldapSession);
return 0;
}