.Net IPAddress IPv4

前端 未结 3 2038
悲&欢浪女
悲&欢浪女 2021-02-06 05:52

I have the following code:

Dim ipAdd As IPAddress = Dns.GetHostEntry(strHostname).AddressList(0)
Dim strIP As String = ipAdd.ToString()

When I

相关标签:
3条回答
  • 2021-02-06 06:28

    For me the solution with the "First" predicate did not work properly, this is the code that works for me:

    public static string GetLocalIP() 
            {
                string ipv4Address = String.Empty;
    
                foreach (IPAddress currrentIPAddress in Dns.GetHostAddresses(Dns.GetHostName()))
                {
                    if (currrentIPAddress.AddressFamily.ToString() == System.Net.Sockets.AddressFamily.InterNetwork.ToString())
                    {
                        ipv4Address = currrentIPAddress.ToString();
                        break;
                    }
                }
    
                return ipv4Address;
            }
    
    0 讨论(0)
  • 2021-02-06 06:35

    dtb's solution will work in many situations. In many cases, however, users may have multiple v4 IPs setup on their system. Sometimes this is because they have some 'virtual' adapters (from applications like VirtualBox or VMWare) or because they have more than one physical network adapter connected to their computer.

    It goes without saying that in these situations it's important that the correct IP is used. You may want to consider asking the user which IP is appropriate.

    To get a list of usable v4 IPs you can use code similar to:

    'Get an array which contains all available IPs: Dim IPList() As IPAddress = Net.Dns.GetHostEntry(Net.Dns.GetHostName.ToString).AddressList

    'Copy valid IPs from IPList to FinalIPList
    Dim FinalIPList As New ArrayList(IPList.Length)
    For Each IP As IPAddress In IPList
        'We want to keep IPs only if they are IPv4 and not a 'LoopBack' device
        '(an InterNetwork AddressFamily indicates a v4 IP)
        If ((Not IPAddress.IsLoopback(IP)) And (IP.AddressFamily = AddressFamily.InterNetwork)) Then
            FinalIPList.Add(IP)
        End If
    Next IP
    
    0 讨论(0)
  • 2021-02-06 06:48

    Instead of unconditionally taking the first element of the AddressList, you could take the first IPv4 address:

    var address = Dns.GetHostEntry(strHostname)
                     .AddressList
                     .First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
    
    0 讨论(0)
提交回复
热议问题