I'm trying to just make an LDAP connection with Active directory to get the list of users. But I'm not even able to compile the simple code for just authentication with the AD using C++.
I have tried many C++ example programs but only got compilation errors. I really just want to connect with AD using C++ without any errors. So can you please tell me what I'm doing wrong in this code which attempts to add a new user to the AD. I have added the environment details, code and errors below for reference.
CODE:
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib")
#include <windows.h>
#include <lm.h>
#include<iostream>
int main()
{
USER_INFO_1 ui;
DWORD dwLevel = 1;
DWORD dwError = 0;
NET_API_STATUS nStatus;
//
// Set up the USER_INFO_1 structure.
// USER_PRIV_USER: name identifies a user,
// rather than an administrator or a guest.
// UF_SCRIPT: required
//
ui.usri1_name = L"username";
ui.usri1_password = L"password";
ui.usri1_priv = USER_PRIV_USER;
ui.usri1_home_dir = NULL;
ui.usri1_comment = NULL;
ui.usri1_flags = UF_SCRIPT;
ui.usri1_script_path = NULL;
//
// Call the NetUserAdd function, specifying level 1.
//
nStatus = NetUserAdd(L"servername",
dwLevel,
(LPBYTE)&ui,
&dwError);
//
// If the call succeeds, inform the user.
//
if (nStatus == NERR_Success)
fwprintf(stderr, L"User %s has been successfully added on %s\n",
L"user", L"dc");
//
// Otherwise, print the system error.
//
else
fprintf(stderr, "A system error has occurred: %d\n", nStatus);
return 0;
}
ERROR:
PS C:\Users\user\Desktop\Sandbox\Cpp> cd "c:\Users\user\Desktop\Sandbox\Cpp\" ; if ($?) { g++ ldap.cpp -o ldap } ; if ($?) { .\ldap }
ldap.cpp: In function 'int main()':
ldap.cpp:22:20: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
22 | ui.usri1_name = L"username";
| ^~~~~~~~~~~
ldap.cpp:23:24: warning: ISO C++ forbids converting a string constant to 'LPWSTR' {aka 'wchar_t*'} [-Wwrite-strings]
23 | ui.usri1_password = L"password";
| ^~~~~~~~~~~
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user-1~1\AppData\Local\Temp\ccByZfCT.o:ldap.cpp:(.text+0xfb): undefined reference to `NetUserAdd'
collect2.exe: error: ld returned 1 exit status
My system run on Windows 10 64bit Installed MSYS with MinGW64 compiler.
I'm no C++ or MinGW expert, but I have a little experience, and I did some Googling. This is the only error:
undefined reference to `NetUserAdd'
The others are warnings.
By your output, it looks like your command to compile is this:
g++ ldap.cpp -o ldap
Try adding -lnetapi32
to the end of that:
g++ ldap.cpp -o ldap -lnetapi32
If you want to resolve those warnings, I think you can declare variables for the username and password rather than assigning literals directly to the struct:
wchar_t username[] = L"username";
wchar_t password[] = L"password";
ui.usri1_name = username;
ui.usri1_password = password;