Jump to content

VB Resolve HostName from IP


Recommended Posts

Hi,

Im not a programmer, Im more of a modifier. So i use alot of code from google and msdn... This time im trying to get hostnames with reversed DNS in VB 2010.

At first I used:

Dim PCName As IPHostEntry = Dns.GetHostEntry(IPAddress.Parse("10.10.10.10"))
MessageBox.Show(PCName.HostName)

But the delay was huge when i scanned the whole 10.10.x.x subnet, took me hours :thumbup

So i found some code for that on msdn... But I failed to modifie it to my needs. All I get is the IPadress or alot of errors.

This is the code that i tried to modifie to get me the hostname from IP:

    Public GetHostEntryFinished As ManualResetEvent = New ManualResetEvent(False)

' Define the state object for the callback.
' Use hostName to correlate calls with the proper result.
Class ResolveState

Dim hostName As String
Dim resolvedIPs As IPHostEntry

Public Sub New(ByVal host As String)
hostName = host
End Sub

Public Property IPs As IPHostEntry
Get
Return resolvedIPs
End Get
Set(ByVal value As IPHostEntry)
resolvedIPs = value
End Set
End Property

Public Property host As [String]
Get
Return hostName
End Get
Set(ByVal value As [String])
hostName = value
End Set
End Property
End Class


' Record the IPs in the state object for later use.
Public Sub GetHostEntryCallback(ByVal ar As IAsyncResult)

Dim ioContext As ResolveState = ar.AsyncState

ioContext.IPs = Dns.EndGetHostEntry(ar)
GetHostEntryFinished.Set()
End Sub

' Determine the Internet Protocol (IP) addresses for
' this host asynchronously.
Public Sub DoGetHostEntryAsync(ByVal hostname As String)

GetHostEntryFinished.Reset()
Dim ioContext As ResolveState = New ResolveState(hostname)

Dns.BeginGetHostEntry(ioContext.host, AddressOf GetHostEntryCallback, ioContext)

' Wait here until the resolve completes (the callback
' calls .Set())
GetHostEntryFinished.WaitOne()

Console.WriteLine("EndGetHostEntry(" + ioContext.host + ") returns:")
'Console.WriteLine(PCName.HostName)

Dim ip As IPAddress() = ioContext.IPs.AddressList
Dim index As Integer
For index = 0 To ip.Length - 1
Console.WriteLine(ip(index))
Next index

End Sub

I know that i can send either hostname or IP as string to the function. But what do I get in return, where is the hostname, is it hiding?

I can run it out of the box with a hostname like "google.com" and i get several adresses in return. I wan't it to be the other way around.

Please say that this is a hard question and that you wheren't able to find the answer on google....Cuz ive tried!

Link to comment
Share on other sites


Ok, maybe I could been a bit more patient and read thrue the code one more time...

Anyway this is what I came up with when I modified the code from MSDN:

 Imports System
Imports System.Net
Imports System.Threading


Module Module1
Sub Main()
DoGetHostEntryAsync("10.10.10.10")
While 1 = 1

End While
End Sub
Public GetHostEntryFinished As ManualResetEvent = New ManualResetEvent(False)

' Define the state object for the callback.
' Use hostName to correlate calls with the proper result.
Class ResolveState

Dim hostName As String
Dim resolvedIPs As IPHostEntry

Public Sub New(ByVal host As String)
hostName = host
End Sub

Public Property IPs As IPHostEntry
Get
Return resolvedIPs
End Get
Set(ByVal value As IPHostEntry)
resolvedIPs = value
End Set
End Property

Public Property host As [String]
Get
Return hostName
End Get
Set(ByVal value As [String])
hostName = value
End Set
End Property
End Class


' Record the IPs in the state object for later use.
Public Sub GetHostEntryCallback(ByVal ar As IAsyncResult)

Dim ioContext As ResolveState = ar.AsyncState

ioContext.IPs = Dns.EndGetHostEntry(ar)
GetHostEntryFinished.Set()
End Sub

' Determine the Internet Protocol (IP) addresses for
' this host asynchronously.
Public Sub DoGetHostEntryAsync(ByVal hostname As String)

GetHostEntryFinished.Reset()
Dim ioContext As ResolveState = New ResolveState(hostname)

Dns.BeginGetHostEntry(ioContext.host, AddressOf GetHostEntryCallback, ioContext)

' Wait here until the resolve completes (the callback
' calls .Set())
GetHostEntryFinished.WaitOne()

Dim ip As IPAddress = ioContext.IPs.AddressList(0)
Dim PCName As String = ioContext.IPs.HostName
Console.WriteLine("IP : " & ip.ToString & " HOST : " & PCName)

End Sub
End Module

Link to comment
Share on other sites

I tried to implement the code on a windowsform with 4 buttons and a DataGridView. But it's still a bit slow when I try to scan the subnet (15 min). I guess its cuz the application doesnt start more than one thread, it waits for the function to finish before it starts a new thread.

Im gonna have a look around and see if somebody else has a better solution to this....

Anyway heres my code so far (badly commented), feel free to make adjustments and pls tell me where I've made stupid things happen:

Imports System
Imports System.Net
Imports System.Threading

Public Class Form1

Public GetHostEntryFinished As ManualResetEvent = New ManualResetEvent(False)

Class ResolveState

Dim hostName As String
Dim resolvedIPs As IPHostEntry

Public Sub New(ByVal host As String)
hostName = host
End Sub

Public Property IPs As IPHostEntry
Get
Return resolvedIPs
End Get
Set(ByVal value As IPHostEntry)
resolvedIPs = value
End Set
End Property

Public Property host As [String]
Get
Return hostName
End Get
Set(ByVal value As [String])
hostName = value
End Set
End Property
End Class


' Record the IPs in the state object for later use.
Public Sub GetHostEntryCallback(ByVal ar As IAsyncResult)
On Error GoTo StopGetCallback
Dim ioContext As ResolveState = ar.AsyncState
ioContext.IPs = Dns.EndGetHostEntry(ar)
StopGetCallback:
GetHostEntryFinished.Set()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 2
DataGridView1.Columns(0).Name = "Hostname"
DataGridView1.Columns(1).Name = "IP"
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' X button
Me.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' _ Button
Me.WindowState = FormWindowState.Minimized
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim i As Long
Dim j As Long

'Loop thrue addresses
For i = 183 To 189
For j = 1 To 254
Try
DoGetHostEntryAsync("10.110." & i & "." & j)
Catch
GoTo ResolveHost
End Try
ResolveHost:
Next
Next
End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
'Fullscreen
Me.Location = New Point(0, 0)
Me.Width = Screen.PrimaryScreen.WorkingArea.Width
Me.Height = Screen.PrimaryScreen.WorkingArea.Height
Button1.Location = New Point(Screen.PrimaryScreen.WorkingArea.Width - 47, 3)
Button2.Location = New Point(Screen.PrimaryScreen.WorkingArea.Width - 25, 3)
Button4.Enabled = False
Button4.Hide()
DataGridView1.Width = Screen.PrimaryScreen.WorkingArea.Width - 40
DataGridView1.Height = Screen.PrimaryScreen.WorkingArea.Height - 60
DataGridView1.Location = New Point(20, 40)

End Sub
Public Sub DoGetHostEntryAsync(ByVal hostname As String)
On Error GoTo StopDoGetHost

Dim Row As String()
GetHostEntryFinished.Reset()
Dim ioContext As ResolveState = New ResolveState(hostname)

Dns.BeginGetHostEntry(ioContext.host, AddressOf GetHostEntryCallback, ioContext)

' Wait here until the resolve completes (the callback
' calls .Set())
GetHostEntryFinished.WaitOne()

'Add to datagrid
Dim ip As IPAddress = ioContext.IPs.AddressList(0)
Dim PCName As String = ioContext.IPs.HostName
Row = {PCName, ip.ToString}
DataGridView1.Rows.Add(Row)

StopDoGetHost:
End Sub
End Class

Link to comment
Share on other sites

I tried to make threads. But the program started acting wierd.... At first run it doesnt list anything in the DataGridView and on the second run it only lists a few hostnames. But on the upside its a bit faster.

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim i As Long
Dim j As Long

'Loop thrue addresses'
For i = 183 To 189
For j = 1 To 254
Try
Dim trd As New Thread(AddressOf DoGetHostEntryAsync)
trd.IsBackground = True
trd.Start("10.110." & i & "." & j)
Catch
GoTo ResolveHost
End Try
ResolveHost:
Next
Next
End Sub

Edited by pany03
Link to comment
Share on other sites

I do not know if this will help you, but here is a app made from VB.Net 2008

MyApp.png

You can then list idividual results from the first querry

MyApp1.png

You can save the results.

MyApp2.png

Here is the code


Imports System
Imports System.IO
Imports System.Net

Public Class Form1
''' <summary>
''' Coded By Gunsmokingman Aka Jake1Eye Aka Ed
''' </summary>
Dim Ln = "------------------------------------------------------------------------------"
'-> Ping Then Enumarate Ip Address
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Select Case Button1.Text
Case "Submit"
Try
If My.Computer.Network.Ping(IpTxt.Text) Then
EnumarateIp(IpTxt.Text)
Button1.Text = "Clear"
Else
MsgBox("Could Not Ping This Addres : " & IpTxt.Text)
End If
Catch ex As Exception
MsgBox("Error : There Was No Valid Ip Address" & vbCrLf & _
"Or There Is No Valid Internet Address", MsgBoxStyle.Exclamation)
IpTxt.Text = ""
End Try
Case "Clear"
Button1.Text = "Submit"
IpTxt.Text = ""
ListBox1.Items.Clear()
End Select
End Sub
'-> Return Ip Addresses
Private Sub EnumarateIp(ByVal IpTest)
Dim hostInfo As IPHostEntry = Dns.GetHostEntry(IpTest)
ListBox1.Items.Add("Host Name : " & hostInfo.HostName)
ListBox1.Items.Add(Ln)
For i = 0 To hostInfo.AddressList.Length - 1
ListBox1.Items.Add("Address List : " & hostInfo.AddressList(i).ToString)
Next
ListBox1.Items.Add(Ln)
End Sub
'-> Save The Information
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If ListBox1.Items.Count = 0 Then
MsgBox("Error There Was No Information To Save")
Else
Dim Nw = "_" & Microsoft.VisualBasic.Replace(Date.Today, "/", "") & "_"
Dim Tm = Microsoft.VisualBasic.Replace(TimeOfDay, ":", "")
Dim Tn = Microsoft.VisualBasic.Replace(Tm, " ", "")
Dim Cm = My.Computer.Name & Nw & Tn & "_ResolveHostName.txt"
Dim Dt = My.Computer.FileSystem.SpecialDirectories.Desktop.ToString & "\" & Cm
Dim sw As StreamWriter = New StreamWriter(Dt.ToString)
For i = 0 To ListBox1.Items.Count - 1
sw.WriteLine(ListBox1.Items.Item(i))
Next
sw.Close()
Process.Start(Chr(34) & Dt.ToString & Chr(34))
End If
End Sub
'-> Selection From Listbox1 To Get Individual Results
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
ListBox1.Items.Add(vbCrLf)
For i = 0 To ListBox1.Items.Count - 1
If InStr(ListBox1.SelectedItem, "Address") Then
If ListBox1.SelectedItem = ListBox1.Items.Item(i) Then
Dim A1 = Split(ListBox1.SelectedItem, " : ")
IpTxt.Text = A1(1)
EnumarateIp(A1(1))
End If
End If
Next
End Sub
End Class

Source Code

Link to comment
Share on other sites

Thanks, I will have a look at it. Last night I tried to stop and whait for every 50th thread, like this:

                    If j <> 50 And j <> 100 And j <> 150 And j <> 200 And j <> 250 Then
Dim trd As New Thread(AddressOf DoGetHostEntryAsync)
trd.IsBackground = True
trd.Start("10.110." & i & "." & j)
Else
Dim trd As New Thread(AddressOf DoGetHostEntryAsync)
trd.IsBackground = True
trd.Start("10.110." & i & "." & j)
trd.Join()
End If

But the program crashed after taking all the recources, both cpu and mem. I didnt know threads could be so complicated :wacko:

Edited by pany03
Link to comment
Share on other sites

Haha this starting to get so wierd... Im trying to use threads which Ive never used before on a function which I know little about.

Anyway this is the code so far and it doesnt list anything in the datagridview but it runs pretty fast :thumbup

Imports System
Imports System.Net
Imports System.Threading

Public Class Form1

Public Rows As List(Of String())
Public GetHostEntryFinished As ManualResetEvent = New ManualResetEvent(False)

Class ResolveState

Dim hostName As String
Dim resolvedIPs As IPHostEntry

Public Sub New(ByVal host As String)
hostName = host
End Sub

Public Property IPs As IPHostEntry
Get
Return resolvedIPs
End Get
Set(ByVal value As IPHostEntry)
resolvedIPs = value
End Set
End Property

Public Property host As [String]
Get
Return hostName
End Get
Set(ByVal value As [String])
hostName = value
End Set
End Property
End Class


' Record the IPs in the state object for later use.
Public Sub GetHostEntryCallback(ByVal ar As IAsyncResult)
On Error GoTo StopGetCallback
Dim ioContext As ResolveState = ar.AsyncState
ioContext.IPs = Dns.EndGetHostEntry(ar)
StopGetCallback:
GetHostEntryFinished.Set()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 2
DataGridView1.Columns(0).Name = "Hostname"
DataGridView1.Columns(1).Name = "IP"
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' X button
Me.Close()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' _ Button
Me.WindowState = FormWindowState.Minimized
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim i As Long
Dim j As Long

'Loop thrue addresses
For i = 183 To 189
For j = 1 To 254
Try

If j <> 50 And j <> 100 And j <> 150 And j <> 200 And j <> 250 And (i <> 189 Or j <> 254) Then
Dim trd As New Thread(AddressOf DoGetHostEntryAsync)
trd.IsBackground = True
trd.Start("10.110." & i & "." & j)
Else
Dim trd2 As New Thread(AddressOf DoGetHostEntryAsync)
trd2.IsBackground = True
trd2.Start("10.110." & i & "." & j)
trd2.Join()
End If

Catch
GoTo ResolveHost
End Try
ResolveHost:
Next
ProgressBar1.Value = ProgressBar1.Value + 13
Next

Try
DataGridView1.DataSource = Rows
Catch
'What to do?
End Try

ProgressBar1.Value = 0

End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
'Fullscreen
Me.Location = New Point(0, 0)
Me.Width = Screen.PrimaryScreen.WorkingArea.Width
Me.Height = Screen.PrimaryScreen.WorkingArea.Height
Button1.Location = New Point(Screen.PrimaryScreen.WorkingArea.Width - 47, 3)
Button2.Location = New Point(Screen.PrimaryScreen.WorkingArea.Width - 25, 3)
Button4.Enabled = False
Button4.Hide()
DataGridView1.Width = Screen.PrimaryScreen.WorkingArea.Width - 40
DataGridView1.Height = Screen.PrimaryScreen.WorkingArea.Height - 60
DataGridView1.Location = New Point(20, 40)

End Sub
Public Sub DoGetHostEntryAsync(ByVal hostname As String)
On Error GoTo StopDoGetHost

GetHostEntryFinished.Reset()
Dim ioContext As ResolveState = New ResolveState(hostname)

Dns.BeginGetHostEntry(ioContext.host, AddressOf GetHostEntryCallback, ioContext)

WaitHandle.WaitAny(New WaitHandle() {GetHostEntryFinished}, 1000)
'GetHostEntryFinished.WaitOne()

Dim PCName As String = ioContext.IPs.HostName
Rows.Add({PCName, hostname})

StopDoGetHost:
End Sub
End Class

BTW Ive looked fairly little on your code gunsmokingman, so far. I will give it a go tonight.

Edited by pany03
Link to comment
Share on other sites

Hi finally something that works and pretty fast aswell... I would have liked to use threads for this but it just didnt wright anything in the grid.

Anyway heres the code and if you want to try it out add a progressbar1, button1 and a datagridview1 to your form.

Imports System
Imports System.Net
Imports System.Threading

Public Class Form1

Public GetHostEntryFinished As ManualResetEvent = New ManualResetEvent(False)

Class ResolveState

Dim hostName As String
Dim resolvedIPs As IPHostEntry

Public Sub New(ByVal host As String)
hostName = host
End Sub

Public Property IPs As IPHostEntry
Get
Return resolvedIPs
End Get
Set(ByVal value As IPHostEntry)
resolvedIPs = value
End Set
End Property

Public Property host As [String]
Get
Return hostName
End Get
Set(ByVal value As [String])
hostName = value
End Set
End Property
End Class


' Record the IPs in the state object for later use.
Public Sub GetHostEntryCallback(ByVal ar As IAsyncResult)
On Error GoTo StopGetCallback
Dim ioContext As ResolveState = ar.AsyncState
ioContext.IPs = Dns.EndGetHostEntry(ar)
StopGetCallback:
GetHostEntryFinished.Set()
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 2
DataGridView1.Columns(0).Name = "Hostname"
DataGridView1.Columns(1).Name = "IP"
DataGridView1.RowHeadersVisible = False
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Long
Dim j As Long
DataGridView1.Rows.Clear()

'Loop thrue addresses
For i = 183 To 189
For j = 1 To 254
Try
'Call function that gets the hotname for us
DoGetHostEntryAsync("10.110." & i & "." & j)

Catch
GoTo ResolveHost
End Try
ResolveHost:
Next
If ProgressBar1.Value < 85 Then
ProgressBar1.Value = ProgressBar1.Value + 15
Else
ProgressBar1.Value = 100
End If
Next

ProgressBar1.Value = 0

End Sub
Public Sub DoGetHostEntryAsync(ByVal hostname As String)
On Error GoTo StopDoGetHost

GetHostEntryFinished.Reset()
Dim ioContext As ResolveState = New ResolveState(hostname)

'Query DNS
Dns.BeginGetHostEntry(ioContext.host, AddressOf GetHostEntryCallback, ioContext)

'Wait for DNS Query
WaitHandle.WaitAny(New WaitHandle() {GetHostEntryFinished}, 1000)

'Resolve hotname and put in the grid right beside TRON
Dim PCName As String = ioContext.IPs.HostName
SetData({PCName, hostname})

StopDoGetHost:
End Sub
Private Sub SetData(ByVal [text] As String())
On Error GoTo CouldntAddRow
Me.DataGridView1.Rows.Add([text])
CouldntAddRow:
End Sub
End Class

Maybe I should go ahead and tag this thread with.... dns.begingethostentry , resolve hostname , networkscanner , VB?

Oops I did.

If somebody knows how to thread this code and still be able to wright to the datagrid.... pls make a post.

Link to comment
Share on other sites

Thats wierd, when I run it on a windows server 2008 machine its slow. But when I run it on my local xp machine it takes about 30sec to fin. Maybe I should tweak the wait abit more, 1000ms is pretty slow for a DNS call.

Link to comment
Share on other sites

  • 4 weeks later...

Hi,

eventually I gave up on trying to resolve DNS with VB and used nmap instead. I use nmap to do a ping scan and save the result in an xml file, then I read the nmap xml file and list all hosts in the grid.

But I didnt want a program that just read an xml file so I added an vnc connect column.

Like this...

Run the nmap bat and read the xml:

     Private Sub Nmap()
Dim Proc As System.Diagnostics.Process
Dim nmaprun As New System.Diagnostics.ProcessStartInfo("nmap.bat")
nmaprun.WindowStyle = ProcessWindowStyle.Hidden
Proc = System.Diagnostics.Process.Start(nmaprun)
Proc.WaitForExit()
readXML()
End Sub

Private Sub readXML()
Dim dtgvupdate As New DataTable
Dim xmldoc As XmlDocument
Dim xml_nodelist As XmlNodeList
Dim xml_node As XmlNode
Dim address As String
Dim name As String

If (File.Exists("scan.xml")) Then
xmldoc = New XmlDocument()
xmldoc.Load("scan.xml")

dtgvupdate.Columns.Add(New DataColumn("IP"))
dtgvupdate.Columns.Add(New DataColumn("Hostname"))

xml_nodelist = xmldoc.SelectNodes("/nmaprun/host/hostnames")

For Each xml_node In xml_nodelist
If xml_node.HasChildNodes Then

address = xml_node.ParentNode.SelectSingleNode("address").Attributes("addr").Value
name = xml_node.SelectSingleNode("hostname").Attributes("name").Value
dtgvupdate.Rows.Add(address, name)

xml_node.RemoveAll()

End If
Next
DataGridView1.DataSource = dtgvupdate
CreateGraphicsColumn()
Else
MessageBox.Show("No xml file")
End If
End Sub

Add a VNC-connect column:

    Public Sub CreateGraphicsColumn()
Try
Dim vncIcon As New Icon("vnc.ico")
Dim iconColumn As New DataGridViewImageColumn()

With iconColumn
.Image = vncIcon.ToBitmap()
.Name = "VNC"
.HeaderText = "VNC"
End With

DataGridView1.Columns.Insert(2, iconColumn)
DataGridView1.Columns(2).Width = 80
Catch
Dim tempcolumn As New DataGridViewButtonColumn
DataGridView1.Columns.Insert(2, tempcolumn)
DataGridView1.Columns(2).Name = "VNC"
End Try
End Sub

Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim ip As String

Try
If e.ColumnIndex = 2 Then
ip = DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString
Dim writer As System.IO.StreamWriter
writer = File.CreateText("connection.bat")
writer.Write("vncviewer.exe " & ip & " -password password")
writer.Close()
OpenVNC()
End If
Catch
MessageBox.Show("Couldn't write .vnc file")
End Try
End Sub
Sub OpenVNC()
Try
Dim Proc As System.Diagnostics.Process
Dim vncrun As New System.Diagnostics.ProcessStartInfo("connection.bat")
vncrun.WindowStyle = ProcessWindowStyle.Hidden
Proc = System.Diagnostics.Process.Start(vncrun)
Catch
MessageBox.Show("Couldn't open VNC")
End Try
End Sub

BTW i use UVNC viewer to connect to hosts.

Edited by pany03
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...