Get IPv4 addresses from Dns.GetHostEntry()

前端 未结 7 1509
长发绾君心
长发绾君心 2020-11-27 04:49

I\'ve got some code here that works great on IPv4 machines, but on our build server (an IPv6) it fails. In a nutshell:

IPHostEntry ipHostEntry = Dns.GetHost         


        
相关标签:
7条回答
  • 2020-11-27 05:16
        public Form1()
        {
            InitializeComponent();
    
            string myHost = System.Net.Dns.GetHostName();
            string myIP = null;
    
            for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
            {
                if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
                {
                    myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
                }
            }
        }
    

    Declare myIP and myHost in public Variable and use in any function of the form.

    0 讨论(0)
  • 2020-11-27 05:23
        public static string GetIPAddress(string hostname)
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(hostname);
    
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    //System.Diagnostics.Debug.WriteLine("LocalIPadress: " + ip);
                    return ip.ToString();
                }
            }
            return string.Empty;
        }
    
    0 讨论(0)
  • 2020-11-27 05:25

    Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?

    0 讨论(0)
  • 2020-11-27 05:25

    To find all valid address list this is the code I have used

    public static IEnumerable<string> GetAddresses()
    {
          var host = Dns.GetHostEntry(Dns.GetHostName());
          return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
    }
    
    0 讨论(0)
  • 2020-11-27 05:31

    IPv6

    lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()


    IPv4

    lblIP.Text = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(1).ToString()

    0 讨论(0)
  • 2020-11-27 05:35

    To find all local IPv4 addresses:

    IPAddress[] ipv4Addresses = Array.FindAll(
        Dns.GetHostEntry(string.Empty).AddressList,
        a => a.AddressFamily == AddressFamily.InterNetwork);
    

    or use Array.Find or Array.FindLast if you just want one.

    0 讨论(0)
提交回复
热议问题