[c#] Get IPv4 addresses from Dns.GetHostEntry()

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.GetHostEntry(string.Empty);

The documentation for GetHostEntry says that passing in string.Empty will get you the IPv4 address of the localhost. This is what I want. The problem is that it's returning the string "::1:" on our IPv6 machine, which I believe is the IPv6 address.

Pinging the machine from any other IPv4 machine gives a good IPv4 address... and doing a "ping -4 machinename" from itself gives the correct IPv4 address.... but pinging it regularly from itself gives "::1:".

How can I get the IPv4 for this machine, from itself?

This question is related to c# .net dns ipv6 ipv4

The answer is


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();
}

    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;
    }

IPHostEntry ipHostInfo = Dns.GetHostEntry(serverName);
IPAddress ipAddress = ipHostInfo.AddressList
    .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

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.


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()


    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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to dns

How is VIP swapping + CNAMEs better than IP swapping + A records? ping: google.com: Temporary failure in name resolution What's the source of Error: getaddrinfo EAI_AGAIN? How do I solve the "server DNS address could not be found" error on Windows 10? Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID How to force DNS refresh for a website? ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known How to filter wireshark to see only dns queries that are sent/received from/by my computer? How can I list ALL DNS records? How to redirect DNS to different ports

Examples related to ipv6

What is IPV6 for localhost and 0.0.0.0? Make docker use IPv4 for port binding How to set java.net.preferIPv4Stack=true at runtime? what does "dead beef" mean? How can I convert IPV6 address to IPV4 address? Get IPv4 addresses from Dns.GetHostEntry() Is there a way for non-root processes to bind to "privileged" ports on Linux? How do ports work with IPv6? Maximum length of the textual representation of an IPv6 address? Regular expression that matches valid IPv6 addresses

Examples related to ipv4

What is IPV6 for localhost and 0.0.0.0? How to set java.net.preferIPv4Stack=true at runtime? Validating IPv4 addresses with regexp How can I convert IPV6 address to IPV4 address? What is the total amount of public IPv4 addresses? What is the largest Safe UDP Packet Size on the Internet Get IPv4 addresses from Dns.GetHostEntry() How to convert an IPv4 address into a integer in C#?