Walt Ritscher: Thinking about code

Thoughts about .Net - Thoughts about code

  Home :: Contact :: Syndication  :: Login
  171 Posts :: 0 Stories :: 80 Comments :: 23 Trackbacks

Archives

Post Categories

Image Galleries

About Me

Interesting Blogs

My other blogs

Resources

If you ever need to get the IP Address of the local computer you need look no further than the System.Net.Dns class.  Since a computer can have more than one IP Address you need to iterate throught the collection.  Here is a sample that fills a listbox with all the IP addresses from your computer.

Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Try

' IpHostEntry is a helper class for the Dns class
' Environment.MachineName should return local computername

Dim hostServer As IPHostEntry = Dns.Resolve(Environment.MachineName)

' assume that we only have IPv4 address
' if you are using IPv6 then you can test with ip.AddressFamily

For Each ip As IPAddress In hostServer.AddressList

' Display the server IP address in the standard format.
' IPv4 it will be in dotted-quad notation
' IPv6 it will be in colon-hexadecimal notation.

   Me.ListBox1.Items.Add(ip.ToString)

Next

Catch ex As Exception
   Console.WriteLine(ex.Message)
End Try

End Sub


posted on Tuesday, March 23, 2004 5:36 PM

Feedback

# re: Finding a local IpAddress 4/22/2004 6:50 PM Brian Pulliam
Question on this code snippet. I had to modify it somewhat in order to get the syntax to work out correctly.

Mainly I added System.Net as a qualifier, and had to Dim ip outside of the for loop, for some weird reason. My machine warns that ip is undeclared. Also had to remove "Me.". Does your snippet work as-is?

Dim hostServer As System.Net.IPHostEntry =_
System.Net.Dns.Resolve(Environment.MachineName)

Dim ip As System.Net.IPAddress

For Each ip In hostServer.AddressList

ListBox1.Items.Add(ip.ToString)


------------

Brian
bryp@hotmail.com

Comments Closed! Due to the spam creeps.
If you want to comment, use the contact page and send me an email and the URL of this Post.
Title  
Name  
Url

Comments   
Enter the code you see: