Solved

Obtain hostname from IP address

Posted on 2004-03-30
2
1,041 Views
Last Modified: 2013-11-13
Anyone have a code snippet that will retrieve a machine name from an IP address?

TIA

-M
0
Comment
Question by:MELeBlanc
2 Comments
 
LVL 67

Accepted Solution

by:
sirbounty earned 50 total points
ID: 10716596
See this link:
http://www.vbip.com/winsock-api/gethostbyaddr/gethostbyaddr-01.asp
>>
In this tutorial we'll learn how to use the gethostbyaddr Winsock API function in order to retrieve a host name by known IP address. Below is the Visual Basic declaration of the function:

Declare Function gethostbyaddr Lib "ws2_32.dll" (addr As Long, _
                                                 ByVal addr_len As Long, _
                                                 ByVal addr_type As Long) As Long

The function returns a pointer to the HOSTENT structure that we already mentioned in the "How to get an IP address of the remote host" tutorial.

Type HOSTENT
    hName     As Long
    hAliases  As Long
    hAddrType As Integer
    hLength   As Integer
    hAddrList As Long
End Type

If the function execution is successful, the hName member of the structure contains a pointer to the host name string. So the VB code to retrieve the host name looks like this one:

'Get the pointer to the HostEnt structure
lngPtrHostEnt = gethostbyaddr(lngInetAdr, 4, PF_INET)
'
'Copy data into the HostEnt structure
RtlMoveMemory udtHostEnt, ByVal lngPtrHostEnt, LenB(udtHostEnt)
'
'Prepare the buffer to receive a string
strHostName = String(256, 0)
'
'Copy the host name into the strHostName variable
RtlMoveMemory ByVal strHostName, ByVal udtHostEnt.hName, 256
'
'Cut received string by first chr(0) character
strHostName = Left(strHostName, InStr(1, strHostName, Chr(0)) - 1)
 
<<
0
 
LVL 8

Expert Comment

by:plq
ID: 10716678
You can read it from the registry if remote registry is enabled

Or you can read it from netbios, or you can try both, for maximum results !!!

REMOTE REG METHOD ...

Private Function GetNameFromReg(sIP As String) As String
   
    '   Return a computer name using remote registry
   
    Dim sResult As String
    Dim reg As New RemoteReg
   
    sResult = reg.GetValue(eHKEY_LOCAL_MACHINE, "SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName", "ComputerName", sIP)
    GetNameFromReg = sResult
   
End Function


and this was in the remote reg class...

Public Function GetValue(ByVal PredefinedKey As HKEYs, ByVal KeyName As String, ByVal ValueName As String, Optional ComputerName As String) As Variant
    On Error GoTo ErrHand
   
    Dim GetHandle As Long
    Dim hKey As Long
    Dim lpData As String
    Dim lpDataDWORD As Long
    Dim lpcbData As Long
    Dim lpType As Long
    Dim lReturnCode As Long
    Dim lhRemoteRegistry As Long
   
    If Left$(KeyName, 1) = "\" Then
        KeyName = Right$(KeyName, Len(KeyName) - 1)
    End If
   
    If ComputerName = "" Then
        GetHandle = RegOpenKeyEx(PredefinedKey, KeyName, 0, KEY_ALL_ACCESS, hKey)
    Else
        lReturnCode = RegConnectRegistry(ComputerName, PredefinedKey, lhRemoteRegistry)
        GetHandle = RegOpenKeyEx(lhRemoteRegistry, KeyName, 0, KEY_ALL_ACCESS, hKey)
    End If
           
    If GetHandle = ERROR_SUCCESS Then
        lpcbData = 255
        lpData = String(lpcbData, Chr(0))
       
        GetHandle = RegQueryValueEx(hKey, ValueName, 0, lpType, ByVal lpData, lpcbData)
           
        If GetHandle = ERROR_SUCCESS Then
            Select Case lpType
                Case REG_SZ
                    GetHandle = RegQueryValueExString(hKey, ValueName, 0, lpType, ByVal lpData, lpcbData)
               
                    If GetHandle = 0 Then
                        GetValue = Left$(lpData, lpcbData - 1)
                    Else
                        GetValue = ""
                    End If
                   
                Case REG_DWORD
                    GetHandle = RegQueryValueEx(hKey, ValueName, 0, lpType, lpDataDWORD, lpcbData)
                   
                    If GetHandle = 0 Then
                        GetValue = CLng(lpDataDWORD)
                    Else
                        GetValue = 0
                    End If
                Case REG_BINARY
                    GetHandle = RegQueryValueEx(hKey, ValueName, 0, lpType, lpDataDWORD, lpcbData)
                   
                    If GetHandle = 0 Then
                        GetValue = CByte(lpDataDWORD)
                    Else
                        GetValue = 0
                    End If
            End Select
        End If
       
        RegCloseKey hKey
    End If
   
    Exit Function

ErrHand:
    Err.Raise "11002", "clsRegistry", "GetValue"
End Function



WINSOCK METHOD ....



Option Explicit

Private Const BIF_BROWSEFORCOMPUTER = &H1000
     
Const WSADESCRIPTION_LEN = 256 + 1
Const WSASYS_STATUS_LEN = 128 + 1
Const AF_INET = 2
Const INADDR_NONE = &HFFFFFFFF

Private Type WSADATA
    wHighVersion As Long
    szDescription As String * WSADESCRIPTION_LEN
    szSystemStatus As String * WSASYS_STATUS_LEN
    iMaxSockets As Long
    iMaxUdpDg As Long
    lpVendorInfo As Long
End Type

Private Type HOSTENT
    h_name As Long 'LPSTR
    h_aliases As Long 'LPLPSTR
    h_addrtype As Integer
    h_length As Integer
    h_addr_list As Long 'char FAR * FAR * h_addr_list
End Type
         
Private Type sockaddr_in
        sin_family As Long
        sin_port As Integer
        in_addr As Long
        sin_zero As String * 8
End Type

Private Type in_addr
    b1 As Byte
    b2 As Byte
    b3 As Byte
    b4 As Byte
End Type
                 
Private Declare Function WSAStartup Lib "WSOCK32.DLL" (ByVal wVersionRequested As Integer, ByRef lpWSADATA As WSADATA) As Long
Private Declare Sub WSACleanup Lib "WSOCK32.DLL" ()
Private Declare Function gethostbyaddr Lib "WSOCK32.DLL" (addr As Any, ByVal iLen As Long, ByVal itype As Long) As Long
Private Declare Function getnameinfo Lib "WSOCK32.DLL" (addr As Any, ByVal iLen As Long, ByVal host As String, ByVal hostlen As Long, ByVal serv As String, ByVal servlen As Long, ByVal flags As Long) As Long
Private Declare Function inet_addr Lib "WSOCK32.DLL" (ByVal cp As String) As Long
Private Declare Function gethostbyname Lib "WSOCK32.DLL" (ByVal name As String) As Long 'HOSTENT
Private Declare Function WSAGetLastError Lib "WSOCK32.DLL" () As Long

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As Long) As Long
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, lpString2 As Any) As Long

Public Function GetName(cpAddr As String) As String
   
    Dim Adata As WSADATA
    Dim addr As Long
    Dim p As Long
    Dim host As HOSTENT
    Dim buf As String
    Dim sHost As String
    Dim sServ As String
    Dim sArr() As String
    Dim sWork As String
     
    sWork = ""
     
    If WSAStartup(&H101, Adata) <> 0 Then Exit Function
   
    addr = inet_addr(cpAddr & Chr$(0))
    If addr <> INADDR_NONE Then
     
        p = gethostbyaddr(ByVal VarPtr(addr), 4, AF_INET)
        If p Then
            CopyMemory ByVal VarPtr(host), ByVal p, LenB(host)
            buf = Space(lstrlen(host.h_name))
            lstrcpy buf, ByVal host.h_name
            sWork = Trim(Left(buf, lstrlen(host.h_name)))
        Else
           
        End If
    End If
     
    WSACleanup
   
    If InStr(sWork, ".") > 0 Then
        sArr = Split(sWork, ".")
        If sArr(0) <> "" Then
            sWork = sArr(0)
        End If
    End If
   
    GetName = sWork
   
End Function



0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
This video teaches viewers about errors in exception handling.
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.

758 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now