[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

C/C++ : How to get the remote logged on user from IP address

Posted on 2008-11-19
7
Medium Priority
?
521 Views
Last Modified: 2012-05-05
Hi,

My problem is, I want to retrieve the logged on user on remote machine. I will have remote machine's IP address. Is there any way to retrieve the information which says that the use XXX has been logged on this machine?

Thanks
0
Comment
Question by:deshaw
  • 4
  • 2
7 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 750 total points
ID: 22997659
You could use the following code to list all users on any remote machine:
//--------------------------------------------------------------------
//
// DisplayLocalLogons
//
// Scans the HKEY_USERS key of the specified computer to see who
// has their profile loaded. Returns true if someone is logged on.
//
//--------------------------------------------------------------------
BOOLEAN DisplayLocalLogons( LPWSTR ServerName, LPWSTR UserName  )
{
    BOOLEAN          first = TRUE;
   TCHAR          errorMessage[1024];
   TCHAR          userName[MAX_NAME_STRING], domainName[MAX_NAME_STRING];
   TCHAR          subKeyName[MAX_PATH];
   DWORD          subKeyNameSize, index;
   DWORD          userNameSize, domainNameSize;
   FILETIME     lastWriteTime;
   HKEY          usersKey;
   PSID          sid;
   SID_NAME_USE sidType;
   SID_IDENTIFIER_AUTHORITY authority;
    BYTE          subAuthorityCount;
   DWORD          authorityVal, revision;
   DWORD          subAuthorityVal[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
   
   //
   // Use RegConnectRegistry so that we work with remote computers
   //
    if( ServerName ) {
         
         wprintf(L"Connecting to Registry of %s...", ServerName );
         fflush( stdout );
 
         if( RegConnectRegistry( ServerName, HKEY_USERS, &usersKey ) != ERROR_SUCCESS) {
       
              wprintf(L"\r                                                      \r");
              wprintf( L"Error opening HKEY_USERS for %s\n", ServerName );
              return FALSE;
         }
         wprintf(L"\r                                                      \r");
 
    } else {
 
         if( RegOpenKey( HKEY_USERS, NULL, &usersKey ) != ERROR_SUCCESS ) {
 
              wprintf( errorMessage, L"Error opening HKEY_USERS" );
              PrintWin32Error( errorMessage, GetLastError() );
              return FALSE;
         }
    }
 
    //
   // Enumerate keys under HKEY_USERS
   //
   index = 0;
   subKeyNameSize = sizeof( subKeyName );
   while( RegEnumKeyEx( usersKey, index, subKeyName, &subKeyNameSize,
                        NULL, NULL, NULL, &lastWriteTime ) == ERROR_SUCCESS ) {
 
       //
       // Ignore the default subkey and win2K user class subkeys
       //
       if( wcsicmp( subKeyName, L".default" ) &&
              !wcsstr( subKeyName, L"Classes")) {
 
              //
              // Convert the textual SID into a binary SID
              //
           subAuthorityCount= swscanf( subKeyName, L"S-%d-%x-%lu-%lu-%lu-%lu-%lu-%lu-%lu-%lu",
                                       &revision, &authorityVal,
                                       &subAuthorityVal[0],
                                       &subAuthorityVal[1],
                                       &subAuthorityVal[2],
                                       &subAuthorityVal[3],
                                       &subAuthorityVal[4],
                                       &subAuthorityVal[5],
                                       &subAuthorityVal[6],
                                       &subAuthorityVal[7] );
 
           if( subAuthorityCount >= 3 ) {
 
               subAuthorityCount -= 2;
               
               //
               // Note: we can only deal with authority values
               // of 4 bytes in length
               //
               authority.Value[5] = *(PBYTE) &authorityVal;
               authority.Value[4] = *((PBYTE) &authorityVal+1);
               authority.Value[3] = *((PBYTE) &authorityVal+2);
               authority.Value[2] = *((PBYTE) &authorityVal+3);
               authority.Value[1] = 0;
               authority.Value[0] = 0;
 
                   //
               // Initialize variables for subsequent operations
               //
               sid = NULL;
               userNameSize   = MAX_NAME_STRING;
               domainNameSize = MAX_NAME_STRING;
 
               if( AllocateAndInitializeSid( &authority,
                                              subAuthorityCount,
                                              subAuthorityVal[0],
                                              subAuthorityVal[1],
                                              subAuthorityVal[2],
                                              subAuthorityVal[3],
                                              subAuthorityVal[4],
                                              subAuthorityVal[5],
                                              subAuthorityVal[6],
                                              subAuthorityVal[7],
                                              &sid )) {
 
                        //
                        // We can finally lookup the account name
                        //
                        if( LookupAccountSid( ServerName,
                                                   sid,
                                                    userName,
                                                   &userNameSize,
                                                   domainName,
                                                   &domainNameSize,
                                                   &sidType )) {
 
                             //
                             // We've successfully looked up the user name
                             //
                           if( first && !UserName ) {
                               
                                   wprintf(L"Users logged on locally:\n");
                                  first = FALSE;
                           }
                           if( !UserName || !wcsicmp( UserName, userName )) {
                             
                                first = FALSE;
                                if( UserName ) wprintf(RESETLINE L"%s\\%s logged onto %s locally.\n",
                                                                 domainName, UserName, ServerName );
                                else                 wprintf( L"     %s\\%s\n", domainName, userName );
                           }                              
                         }
               }              
                if( sid ) FreeSid( sid );
           }
       }
       subKeyNameSize = sizeof( subKeyName );
       index++;
   }
    RegCloseKey( usersKey );
 
    if( first && !UserName ) wprintf(L"No one is logged on locally.\n");
    return !first;
}

Open in new window

0
 
LVL 3

Expert Comment

by:SreejithG
ID: 23001643
the source code you are looking for is avilable in
http://read.pudn.com/downloads/sourcecode/windows/system/1439/LOGGEDON.C__.htm
0
 
LVL 1

Author Comment

by:deshaw
ID: 23001775
I have removed most of errors but I am not able to remove below errors. Could anyone tell me how to remove it. One more thing I dont know why this code expect UNICODE defined? I am compiling code in Release mode.

Error259      error C2664: 'wcsicmp' : cannot convert parameter 1 from 'LPSTR' to 'const wchar_t *'            
Error260      error C2665: 'wcsstr' : none of the 2 overloads could convert all the argument types            
Error261      error C2664: 'swscanf' : cannot convert parameter 1 from 'LPSTR' to 'const wchar_t       
Error262      error C2664: 'wcsicmp' : cannot convert parameter 2 from 'LPSTR' to 'const wchar_t *'

Thanks            
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 1

Author Comment

by:deshaw
ID: 23002064
The condition "if( subAuthorityCount >= 3 ) {" never gets true and as a result it always says "No user logged on". Please let me know if you know the reason for this,

Thanks,
0
 
LVL 1

Author Comment

by:deshaw
ID: 23002082
Sorry, missed to tell you that I have used type casting - "(LPSTR)subKeyName"  and all errors went off.

0
 
LVL 86

Expert Comment

by:jkr
ID: 23004787
>>I have used type casting - "(LPSTR)subKeyName"  and all errors went off.

Actually, it is not a good idea to typecast here - bettre set your project to UNICODE to get rid of these issues, this ensures that the code does not only compile but also run.
0
 
LVL 1

Author Closing Comment

by:deshaw
ID: 31518397
Thanks, ikr
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Navigation is an important part of web design from a usability perspective. But it is often a pain when it comes to a developer’s perspective. By navigation, it often means menuing. This is less theory and more practical of how to get a specific gro…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses
Course of the Month18 days, 1 hour left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question