Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting valid IP from IPHostEntry

Tags:

c#

ip-address

I tried to get the IPAddress of my computer using this

        var ipadd = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ipAddress in ipadd.AddressList)
            Console.WriteLine("IP Address: {0}", ipAddress);

I have only one network card in my computer which is connected to the router. It is ipv4 but this line of code gives me 4 IPAddress 3 of them are ipv6 and one is ipv4 which is the valid one. I like to ask why is that so ?

Thanks

like image 392
Ahmed Avatar asked May 06 '26 21:05

Ahmed


1 Answers

foreach (var addr in Dns.GetHostEntry(string.Empty).AddressList)
{
    if (addr.AddressFamily == AddressFamily.InterNetwork)
        Console.WriteLine("IPv4 Address: {0}", addr)
}
like image 53
Richard Schneider Avatar answered May 09 '26 04:05

Richard Schneider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!