Search code examples
c#ipv4

Obtain IPV4 Address by default


IPHostEntry HostInformation = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress IP = HostInformation.AddressList[0].MapToIPv4();
Console.WriteLine(IP.ToString());

Using the above snippet I'm trying to get the IPV4 Address of the current user running the application, my network interface has IPV6 Enabled also. HostInformation is getting populated with a V6 Address:

fe80::d168:1665:65c:7c2e%12

When trying to get:

192.168.0.2

MapToIPV4 returns:

6.92.124.46

Having:

        foreach (var Element in HostInformation.AddressList)
        {
            Console.WriteLine(Element + "\n\n");
        }

Shows Four addresses:

fe80::d168:1665:65c:7c2e%12

fe80::448:ff7:a313:2477%18

192.168.0.2

2001:0:5ef5:79fb:448:ff7:a313:2477

So with that logic, HostInformation.AddressList[2]; would contain my results. But, would that always be a V4 Address? Will the third element in the array always be present? So overall. How to seek the array to find the V4 Address and return the appropriate index?


Solution

  • After searching the documentation based on the comment by @500-InternalServerError I have developed this:

        public IPAddress GetIPV4(IPHostEntry HostInformation)
        {
            IPAddress[] IP = HostInformation.AddressList;
            int index = 0;
            foreach (IPAddress Address in IP)
            {
                if (Address.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    break;
                }
                index++;
            }
            return HostInformation.AddressList[index];
        }
    

    With being invoked by:

    IPAddress IP = GetIPV4(Dns.GetHostEntry(Dns.GetHostName()));
    

    Tested and working on 3 machines each with interfaces/addresses spanning from the 1 V4 to 4 Addresses