Obtain hostname from IP address

Posted on 2004-03-30
Medium Priority
Last Modified: 2013-11-13
Anyone have a code snippet that will retrieve a machine name from an IP address?


Question by:MELeBlanc
LVL 67

Accepted Solution

sirbounty earned 200 total points
ID: 10716596
See this link:
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.

    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)

Expert Comment

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 !!!


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)
        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)
                        GetValue = ""
                    End If
                Case REG_DWORD
                    GetHandle = RegQueryValueEx(hKey, ValueName, 0, lpType, lpDataDWORD, lpcbData)
                    If GetHandle = 0 Then
                        GetValue = CLng(lpDataDWORD)
                        GetValue = 0
                    End If
                Case REG_BINARY
                    GetHandle = RegQueryValueEx(hKey, ValueName, 0, lpType, lpDataDWORD, lpcbData)
                    If GetHandle = 0 Then
                        GetValue = CByte(lpDataDWORD)
                        GetValue = 0
                    End If
            End Select
        End If
        RegCloseKey hKey
    End If
    Exit Function

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


Option Explicit

Const WSASYS_STATUS_LEN = 128 + 1
Const AF_INET = 2

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)))
        End If
    End If
    If InStr(sWork, ".") > 0 Then
        sArr = Split(sWork, ".")
        If sArr(0) <> "" Then
            sWork = sArr(0)
        End If
    End If
    GetName = sWork
End Function


Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

621 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