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!
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With