Getting Logged in Username

BlitzMax Forums/BlitzMax Programming/Getting Logged in Username

Scaremonger(Posted 2013) [#1]
Hi all,

I am able to obtain the username from the environment variables with this code; Unfortunately it can be changed easily to misrepresent the logged in user.
?win32
Function getUserEnvName$()
	Return getenv_("username")
End Function
?linux
Function getUserEnvName$()
	Return getenv_("USER")
End Function
?
print "USERNAME: "+getUserEnvName()

Under Windows you can get the logged in user with a simple API call:
Local advapi32:Int = loadLibraryA( "advapi32.dll" )
Global __GetUserName:Int( ..
	lpBuffer: 	Byte Ptr, ..
	lpnSize:	Byte Ptr ..
	) "Win32" = GetProcAddress( advapi32, "GetUserNameA" )

Function getUserName$()
Local username:Byte[256]
Global size:Int = 256
	If Not __GetUserName Then Return ""
	If __GetUserName( username, Varptr( size ) ) Then 
		Return String.fromCString( username )
	End If
	Return ""
End Function

Print "USERNAME: " + getUserName()

... and I have found a Linux API getuid(), but I get a segmentation fault when I attempt to use it.

Any pointers on what I have missed?
Import "getuid.linux.c"

Extern "c"
Function getuid_$()
End Extern

Function getUserName$()
Return getuid_()	
End Function

Print "USERNAME: " + getUserName()
getuid.linuc.c

#include <brl.mod/blitz.mod/blitz.h>

#include <sys/types.h>
#include <unistd.h>

BBString *getuid_( void ){
	return bbStringFromUTF8String( getuid() );
}



Brucey(Posted 2013) [#2]
According to the manpage, getuid() returns the user id, which is a number.


Brucey(Posted 2013) [#3]
You might find getlogin_r() more useful.


Scaremonger(Posted 2013) [#4]
Cheers Brucey, that explains the Segmentation fault. lol

Unfortunately I keep getting error EINVAL[22] from getlogin_r(). Any suggestions?

getlogin.bmx
?linux
	'#
	'##### int getlogin_r(char *buf, size_t bufsize);
	'#
	Extern "c"
	Function getlogin_r:Int( buf:Byte Ptr, bufsize:Int )
	End Extern

	Function getUserName$()
	Local buf:Byte[1024]
	Local result% = getlogin_r( buf, buf.length )
		If result = 0 Then
			Return String.fromCString( buf )
		Else
			Print "Error: "+result
		End If
	End Function
	
?
Print "USERNAME: " + getUserName()



Brucey(Posted 2013) [#5]
Strange. Your example is working fine for me (Fedora). Prints "USERNAME: brucey".