1 Replies - 390 Views - Last Post: 21 October 2017 - 12:30 PM Rate Topic: -----

#1 Nigels  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 73
  • Joined: 17-May 13

Getting Local IP address from computer name

Posted 21 October 2017 - 12:41 AM

Hi,
I have got a listBox and 2 TextBox's on a windows form the ListBox show's all local computers on my network. When I click on one of the computer names in the listBox it moves the computer name in to a TextBox. It then attempts to get the IP4 address of that computer.
Sometimes it works and other times it seems to give me a load of gobblydook like "ea63dff66ad3956". I have been using this code.

LNComputers = is the name of the ListBox
HostNameTxtBox = the name of the TextBox where I put the selected item from the ListBox
RemoteIP is the name of the TextBox where the ip address is supposed to go.


  If LNComputers.SelectedIndex <> -1 Then
            HostNameTxtBox.Text = LNComputers.GetItemText(LNComputers.SelectedItem)

            Dim hostname As IPHostEntry = Dns.GetHostEntry(HostNameTxtBox.Text)
            Dim ip As IPAddress() = hostname.AddressList
            RemoteIP.Text = ip(0).ToString()


It would be good if someone could help me get the ip4 address every time rather than just now and then.
Thanks Nige.

Is This A Good Question/Topic? 0
  • +

Replies To: Getting Local IP address from computer name

#2 IronRazer  Icon User is offline

  • Custom Control Freak
  • member icon

Reputation: 1447
  • View blog
  • Posts: 3,682
  • Joined: 01-February 13

Re: Getting Local IP address from computer name

Posted 21 October 2017 - 12:30 PM

If you read through the msdn documents on the IPAddress Class, particularly the IsIpxxxx properties. You can use them to try filtering out the IP6 addresses. For example, you could use the Where extension to filter the AddressList as shown below. This could be done with an If Then statement too if you like.

The IPHostEntry.AddressList Property is a list which can contain the Ip6 and IP4 address so, you need to filter them to get what you want from the list. The Ip4 will not always be the first in the list as your code is assuming. It appears your getting the IP6 address from some and the wanted IP4 from the others.

Just for a test, use a loop to iterate through the list and show them all in a listbox, textbox, or whatever. This will give you an idea of what is in the list. Debugging 101. 8)

        If LNComputers.SelectedIndex <> -1 Then
            HostNameTxtBox.Text = LNComputers.GetItemText(LNComputers.SelectedItem)
            Dim hostEntry As IPHostEntry = Dns.GetHostEntry(HostNameTxtBox.Text)
            Dim ip4 As IPAddress = hostEntry.AddressList.Where(Function(a) Not a.IsIPv6LinkLocal AndAlso Not a.IsIPv6Multicast AndAlso Not a.IsIPv6SiteLocal).FirstOrDefault
            RemoteIP.Text = ip4.ToString
        End If


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1