Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 966015
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T02:05:28+00:00 2026-05-16T02:05:28+00:00

I am trying to get the current’s user last logon. I might be this

  • 0

I am trying to get the current’s user last logon. I might be this current session or it might be one before that.
I am calling GetUserName() to get the current username. I feed that into NetUserGetInfo() to try to get the last logon time. All this fails with error 2221 (user not found). When I tried with “administrator” it works. Even when I hardcode my username it returns a 2221. This is what I am using:

nStatus = NetUserGetInfo(NULL, L"administrator", dwLevel, (LPBYTE *) & pBuf);

How can you get the current user’s last logon time?

thank you, code is always welcomed.

Here’s the full code I am currently using:

DWORD dwLevel = 2;
NET_API_STATUS nStatus;
LPTSTR sStringSid = NULL;
LPUSER_INFO_0 pBuf = NULL;
LPUSER_INFO_2 pBuf2 = NULL;
WCHAR UserName[256];
DWORD nUserName = sizeof(UserName); 

if(GetUserName(UserName, &nUserName))
{
    printf("information for %ls\n", UserName);
    nStatus = NetUserGetInfo(NULL, UserName, dwLevel, (LPBYTE *) & pBuf);
    if (nStatus == NERR_Success) 
    {
        pBuf2 = (LPUSER_INFO_2) pBuf;
        printf("\tUser account name: %ls\n", pBuf2->usri2_name);
        printf("\tLast logon (seconds since January 1, 1970 GMT): %d\n", pBuf2->usri2_last_logon);
        printf("\tLast logoff (seconds since January 1, 1970 GMT): %d\n", pBuf2->usri2_last_logoff);
    }
    else
        fprintf(stderr, "NetUserGetinfo failed with error: %d\n", nStatus);

    if (pBuf != NULL)
        NetApiBufferFree(pBuf);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T02:05:29+00:00Added an answer on May 16, 2026 at 2:05 am

    You can try to use other level as 2 for example 11.

    You can aslo try LsaGetLogonSessionData (see http://msdn.microsoft.com/en-us/library/aa378290.aspx). The struct SECURITY_LOGON_SESSION_DATA has a lot of information which can be helpful for you. The LUID (the first parameter of LsaGetLogonSessionData) you can get from GetTokenInformation with TokenStatistics and get AuthenticationId field of the TOKEN_STATISTICS struct.

    UPDATED: I read more carefully your code and I see now your main error. Function NetUserGetInfo is very old. It exists in the time before Windows NT 3.1. The group of functions which Microsoft named now “Network Management” has the name “LAN Manager API”. All the functions were introduced in the time where no local login exists. So you can use NetUserGetInfo with NULL as the first parameter only on a domain controller. So in the case that you login with the domain account you should call NetGetDCName, NetGetAnyDCName or better DsGetDcName to get the name of a domain controller and use this name (started with two backslashes) as the first parameter of NetUserGetInfo. If you login with a local workstation account your program should work, but the account seems me must be UNICODE string like L”Administrator” and not “Administrator”. By the way if I login locally on my Windows 7 64-bit computer your program work without any problem. The code

    nStatus = NetUserGetInfo(NULL, L"administrator", dwLevel, (LPBYTE *) & pBuf);
    

    works also.

    I repeat then in my opinion the best way to get user’s last logon is the usage of LSA (Local Security Authority) API like LsaGetLogonSessionData. How promised I wrote for you a code example which shows how to use LsaGetLogonSessionData in C:

    #include <windows.h>
    #include <Ntsecapi.h>
    #include <Sddl.h>
    #include <tchar.h>
    #include <stdio.h>
    //#include <ntstatus.h>
    #include <malloc.h>
    #include <strsafe.h>
    
    #pragma comment (lib, "Secur32.lib")
    #pragma comment (lib, "strsafe.lib")
    
    // The following constant may be defined by including NtStatus.h.
    #ifndef STATUS_SUCCESS
    #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
    #endif
    // The LSA authentication functions are available in Unicode only.
    
    BOOL GetLogonLUID (LUID *pLuid)
    {
        BOOL bSuccess;
        HANDLE hThread = NULL;
        DWORD cbReturnLength;
        TOKEN_STATISTICS ts;
    
        __try {
            bSuccess = OpenProcessToken (GetCurrentProcess(), TOKEN_QUERY, &hThread);    // TOKEN_QUERY_SOURCE
            if (!bSuccess)
                __leave;
    
            cbReturnLength = sizeof(TOKEN_STATISTICS);
            bSuccess = GetTokenInformation (hThread, TokenStatistics, &ts, sizeof(TOKEN_STATISTICS), &cbReturnLength);
            if (bSuccess)
                *pLuid = ts.AuthenticationId;
        }
        __finally {
            if (hThread)
                CloseHandle (hThread);
        }
    
        return bSuccess;
    }
    
    void PrintUnicodeString (LPCTSTR pszPrefix, LSA_UNICODE_STRING lsaString)
    {
        if (lsaString.MaximumLength >= lsaString.Length + sizeof(WCHAR) &&
            lsaString.Buffer[lsaString.Length/sizeof(WCHAR)] == L'\0')
            _tprintf (TEXT("%s: %ls\n"), pszPrefix, lsaString.Buffer);
        else if (lsaString.Length <= STRSAFE_MAX_CCH * sizeof(TCHAR)) {
            LPWSTR sz = (LPWSTR) _alloca (lsaString.Length + sizeof(WCHAR));
            StringCbCopyNW (sz, lsaString.Length + sizeof(WCHAR), lsaString.Buffer, lsaString.Length);
            _tprintf (TEXT("%s: %ls\n"), pszPrefix, sz);
        }
    }
    
    void PrintLogonType (SECURITY_LOGON_TYPE type)
    {
        if (type < Interactive || type > CachedUnlock)
            // This is used to specify an undefied logon type
            _tprintf (TEXT("LogonType: UndefinedLogonType\n"));
        else {
            static LPTSTR szTypes[] = {
                TEXT("Interactive"),      // Interactively logged on (locally or remotely)
                TEXT("Network"),              // Accessing system via network
                TEXT("Batch"),                // Started via a batch queue
                TEXT("Service"),              // Service started by service controller
                TEXT("Proxy"),                // Proxy logon
                TEXT("Unlock"),               // Unlock workstation
                TEXT("NetworkCleartext"),     // Network logon with cleartext credentials
                TEXT("NewCredentials"),       // Clone caller, new default credentials
                TEXT("RemoteInteractive"),  // Remote, yet interactive. Terminal server
                TEXT("CachedInteractive"),  // Try cached credentials without hitting the net.
                // The types below only exist in Windows Server 2003 and greater
                TEXT("CachedRemoteInteractive"), // Same as RemoteInteractive, this is used internally for auditing purpose
                TEXT("CachedUnlock")        // Cached Unlock workstation
            };
            _tprintf (TEXT("LogonType: %s\n"), szTypes[(int)type-Interactive]);
        }
    }
    
    void PrintFilefime (LPCTSTR pszPrefix, const FILETIME *lpFileTime)
    {
        SYSTEMTIME st;
        FILETIME ft;
        BOOL bSuccess;
        TCHAR szTime[1024], szDate[1024];
    
        bSuccess =  FileTimeToLocalFileTime (lpFileTime, &ft);
        if (!bSuccess)
            return;
        bSuccess = FileTimeToSystemTime (&ft, &st);
        if (!bSuccess)
            return;
    
        if (GetDateFormat (LOCALE_USER_DEFAULT, // or LOCALE_CUSTOM_UI_DEFAULT
                           DATE_SHORTDATE,
                           &st, NULL, szDate, sizeof(szDate)/sizeof(TCHAR)) > 0) {
            if (GetTimeFormat (LOCALE_USER_DEFAULT, // or LOCALE_CUSTOM_UI_DEFAULT
                               0, &st, NULL, szTime, sizeof(szTime)/sizeof(TCHAR)) > 0) {
                _tprintf (TEXT("%s: %s, %s\n"), pszPrefix, szDate, szTime);
            }
        }
    }
    
    int main()
    {
        LUID LogonLuid; // LOGONID_CURRENT
        PSECURITY_LOGON_SESSION_DATA pLogonSessionData = NULL;
        LPWSTR pszSid = NULL;
        NTSTATUS ntStatus;
    
        GetLogonLUID (&LogonLuid);
        __try {
            ntStatus = LsaGetLogonSessionData (&LogonLuid, &pLogonSessionData);
            if (ntStatus == STATUS_SUCCESS) {
                if (pLogonSessionData->UserName.Length)
                    PrintUnicodeString (TEXT("UserName"), pLogonSessionData->UserName);
                if (pLogonSessionData->LogonDomain.Length)
                    PrintUnicodeString (TEXT("LogonDomain"), pLogonSessionData->LogonDomain);
                if (pLogonSessionData->AuthenticationPackage.Length)
                    PrintUnicodeString (TEXT("AuthenticationPackage"), pLogonSessionData->AuthenticationPackage);
                PrintLogonType ((SECURITY_LOGON_TYPE)pLogonSessionData->LogonType);
                _tprintf (TEXT("Session: %d\n"), pLogonSessionData->Session);
                if (ConvertSidToStringSidW (pLogonSessionData->Sid, &pszSid))
                    _tprintf (TEXT("Sid: %ls\n"), pszSid);
                if (pLogonSessionData->LogonTime.QuadPart)
                    PrintFilefime (TEXT("LogonTime"), (const FILETIME *)&pLogonSessionData->LogonTime);
                if (pLogonSessionData->LogonServer.Length)
                    PrintUnicodeString (TEXT("LogonServer"), pLogonSessionData->LogonServer);
                if (pLogonSessionData->DnsDomainName.Length)
                    PrintUnicodeString (TEXT("DnsDomainName"), pLogonSessionData->DnsDomainName);
                if (pLogonSessionData->Upn.Length)
                    PrintUnicodeString (TEXT("Upn"), pLogonSessionData->Upn);
                // one can dump more information like HomeDirectory, ProfilePath and so on
                // if _WIN32_WINNT >= 0x0600 and user login a domain
            }
        }
        __finally {
            if (pLogonSessionData)
                LsaFreeReturnBuffer(pLogonSessionData);
            if (pszSid)
                pszSid = (LPTSTR)LocalFree (pszSid);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to get the current application name (the application that contains the current
I'm trying to get the current user login status via javascript sdk but I
I'm trying to get the current time as TimeStamp without success. I have this
I am trying to get the current longitude and latitude right before the table
i'm trying to get the current date and time formatted, this is my code:
I'm trying to get the current time via DateTime.Now.ToString(yyyy-MM-dd hh:mm:ss) However, this is spitting
I am trying to get current date - 6 days. That is easy. Now
I am trying to get current location of user using CLLocationCoordinate2D. I want the
I'm trying to get the current user's favorite artists. When I use the '/me/music'
I'm trying to get the current machineKey that is being used to encrypt/decrypt my

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.