Link to home
Start Free TrialLog in
Avatar of gtrainer
gtrainer

asked on

How do I resolve a domain name under which a user is logged in?

Please pardon my naivete, this is my first time using the Security API.

I am writing an application that must make a trusted connection to SQL Server.  Therefore, my app needs to pass a user id thus: [Domain name]\[User Name].  The app is running on NT Workstation 4.0  I can resolve the User name with the GetUserName API call, but when I use LookupAccountName to try to get the domain name, the call fails.  Am I using the right call?  If so, what is wrong with the code below that is causing LookupAccountName to fail?  200 points to (s)he who wields a clue.

Private Sub Command1_Click()
Const lBUFFER_SIZE = 254
Dim sSystemName As String
Dim sAccountName As String
Dim lSID As Long
Dim lSIDSize As Long
Dim sDomainName As String
Dim lDomainNameBufferSize As Long
Dim iPENameUse As Integer
Dim lRET As Long

    sSystemName = Chr(0)
    sAccountName = "gtrainer" & Chr(0)
    lSID = 0
    lSIDSize = lBUFFER_SIZE
    lDomainNameBufferSize = lBUFFER_SIZE
    sDomainName = Space(lDomainNameBufferSize - 1) & Chr(0)
    iPENameUse = 0
   
    lRET = LookupAccountName(sSystemName, sAccountName, 0, 0, sDomainName, lDomainNameBufferSize, iPENameUse)
    Debug.Print
    Debug.Print "-----------------------------------------------"
    Debug.Print "Return Code: " & Trim(CStr(lRET))
    Debug.Print "System Name: " & StripNullAndSpaces(sSystemName)
    Debug.Print "Account Name: " & StripNullAndSpaces(sAccountName)
    Debug.Print "Domain Name: " & StripNullAndSpaces(sDomainName)
    Debug.Print "-----------------------------------------------"
    Debug.Print

End Sub

Private Function StripNullAndSpaces(sInput As String) As String
Dim iIndex As Integer
Dim sOutput As String

    sOutput = ""
   
    For iIndex = 1 To Len(sInput)
        If Mid(sInput, iIndex, 1) = Chr(0) Then
            Exit For
        Else
            sOutput = sOutput & Mid(sInput, iIndex, 1)
        End If
    Next iIndex
   
    StripNullAndSpaces = Trim(sOutput)
   
End Function
ASKER CERTIFIED SOLUTION
Avatar of Erick37
Erick37
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gtrainer
gtrainer

ASKER

It worked beautifully!  Thanks for your help!  I have to ask this rhetorical question:

Why on earth does the first call to LookupAccountName give you the length of the domain name, but not the domain name?  Wouldn't it have to know the domain name in order to tell you long it was?  That's like introducing yourself by saying, "Nice to meet you, Jim!  My name has 7 letters in it!"  What an great way to abruptly end a conversation.

Thanks again for your help!


:)
Yes it does, but it allows you to allocate space for the name before actually saving it.

Glad it worked!