Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c - User's login and logout time

is it possible to get user's login and logout time in a objective-c program? I can get the session ID, username, userUID, userIsActive and loginCompleted with CGSessionCopyCurrentDictionary function but I can't get login and logout time from it, can I?

I know I can get the info from console.app, but I would like to put it in a program.

Where do I look for more info on that? Can't find it in Development guide from Apple.

Thanks!

like image 569
Oggy Avatar asked Jan 15 '13 15:01

Oggy


1 Answers

I don't know if there are any special Cocoa function to get user login/logout time.

But you can read the login/logout history directly, using getutxent_wtmp(). This is what the "last" command line tool does, as can be seen in the source code: http://www.opensource.apple.com/source/adv_cmds/adv_cmds-149/last/last.c

Just to give a very simple example: The following program prints all login/logout times to the standard output:

#include <stdio.h>
#include <utmpx.h>

int main(int argc, const char * argv[])
{
    struct utmpx *bp;
    char *ct;

    setutxent_wtmp(0); // 0 = reverse chronological order
    while ((bp = getutxent_wtmp()) != NULL) {
        switch (bp->ut_type) {
            case USER_PROCESS:
                ct = ctime(&bp->ut_tv.tv_sec);
                printf("%s login %s", bp->ut_user, ct);
                break;
            case DEAD_PROCESS:
                ct = ctime(&bp->ut_tv.tv_sec);
                printf("%s logout %s", bp->ut_user, ct);
                break;

            default:
                break;
        }
    };
    endutxent_wtmp();

    return 0;
}

And just for fun: A Swift 4 solution:

import Foundation

extension utmpx {
    var userName: String {
        return withUnsafePointer(to: ut_user) {
            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: ut_user)) {
                String(cString: $0)
            }
        }
    }
    var timestamp: Date {
        return Date(timeIntervalSince1970: TimeInterval(ut_tv.tv_sec))
    }
}

setutxent_wtmp(0)
while let bp = getutxent_wtmp() {

    switch bp.pointee.ut_type {
    case Int16(USER_PROCESS):
        print(bp.pointee.userName, "login", bp.pointee.timestamp)
    case Int16(DEAD_PROCESS):
        print(bp.pointee.userName, "logout", bp.pointee.timestamp)
    default:
        break
    }
}
endutxent_wtmp();
like image 168
Martin R Avatar answered Oct 04 '22 20:10

Martin R